在 C# 的方法中使用 'ref' 关键字作为字符串参数的影响?
Impact of using the 'ref' keyword for string parameters in methods in C#?
作为对 .NET 管道不太了解的程序员,我想知道在 C# 中使用引用字符串作为参数是否有利于提高性能?
假设我有这样的方法:
public int FindSomething(string text)
{
// Finds a char in the text and returns its index
}
当我使用这个方法时,编译器会为该方法创建一个文本副本,对吗?
但是如果我使用 ref
关键字:
public int FindSomething(ref string text)
{
// Finds a char in the text and returns its index
}
..编译器应该只发送文本的指针地址...
那么像这样使用 ref
对性能有好处吗?
When I use this method, the compiler creates a copy of the text for the method, right?
不,不是。 string
是引用类型,编译器将创建一个新的堆栈变量,该变量指向在给定内存地址处表示的相同 string
。它不会复制字符串。
当您在引用类型上使用 ref
时,不会创建指向 string
的指针副本。它只会传递已经创建的引用。这仅在您想要创建一个全新的 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?
性能提升不会很明显。将会发生的是其他开发人员对您为什么使用 ref
传递字符串感到困惑。
作为对 .NET 管道不太了解的程序员,我想知道在 C# 中使用引用字符串作为参数是否有利于提高性能?
假设我有这样的方法:
public int FindSomething(string text)
{
// Finds a char in the text and returns its index
}
当我使用这个方法时,编译器会为该方法创建一个文本副本,对吗?
但是如果我使用 ref
关键字:
public int FindSomething(ref string text)
{
// Finds a char in the text and returns its index
}
..编译器应该只发送文本的指针地址...
那么像这样使用 ref
对性能有好处吗?
When I use this method, the compiler creates a copy of the text for the method, right?
不,不是。 string
是引用类型,编译器将创建一个新的堆栈变量,该变量指向在给定内存地址处表示的相同 string
。它不会复制字符串。
当您在引用类型上使用 ref
时,不会创建指向 string
的指针副本。它只会传递已经创建的引用。这仅在您想要创建一个全新的 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?
性能提升不会很明显。将会发生的是其他开发人员对您为什么使用 ref
传递字符串感到困惑。