As a programmer who don't have a good idea about the .NET pipeline, I was wondering if using ref strings as parameters are good for performance in C#?
Let's say I have a method like this:
public int FindSomething(string text)
{
// Finds a char in the text and returns its index
}
When I use this method, the compiler creates a copy of the text for the method, right?
But if I use the ref
keyword:
public int FindSomething(ref string text)
{
// Finds a char in the text and returns its index
}
.. the compiler should only send the text's pointer address...
So is it good for performance using ref
like this?
When I use this method, the compiler creates a copy of the text for the method, right?
No, it doesn't. string
is a reference type, and the compiler will create a new stack variable which points to the same string
represented at a given memory address. It won't copy the string.
When you use ref
on a reference type, there won't be a copy of the pointer to the string
created. It will simply pass the already created reference. This is useful only when you want to create an entirely new string
:
void Main()
{
string s = "hello";
M(s);
Console.WriteLine(s);
M(ref s);
Console.WriteLine(s);
}
public void M(string s)
{
s = "this won't change the original string";
}
public void M(ref string s)
{
s = "this will change the original string";
}
So is it good for performance using ref like this?
The performance gains won't be noticeable. What will happen is other developers getting confused as to why you used ref
to pass the string.