在适合C#性能的方法中使用'ref'关键字作为字符串参数?

Ibr*_*mir 11 c# string performance ref

作为一个对.NET管道不太了解的程序员,我想知道使用ref字符串作为参数是否有利于C#的性能?

假设我有一个像这样的方法:

public int FindSomething(string text)
{
    //Finds a char in the text and returns its index
}
Run Code Online (Sandbox Code Playgroud)

当我使用这个方法时,编译器会为方法创建一个文本副本,对吧?

但是,如果我使用ref关键字:

public int FindSomething(ref string text)
{
    //Finds a char in the text and returns its index
}
Run Code Online (Sandbox Code Playgroud)

..编译器应该只发送文本的指针地址...

那么使用ref这样的性能有好处吗?

Yuv*_*kov 22

当我使用这个方法时,编译器会为方法创建一个文本副本,对吧?

不,它没有.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";
}
Run Code Online (Sandbox Code Playgroud)

那么使用像这样的ref对性能有好处吗?

性能提升不会明显.会发生什么事情让其他开发人员对你过去ref传递字符串的原因感到困惑.

  • 我的观点是,通过`ref`传递字符串会使代码*变慢*(稍微因为它只是单个 - 缓存 - 读取,但仍然较慢).因此,谈论性能提升是误导性的 - 通过这样做,你最多不会看到性能下降. (3认同)