4

Is it better to transfer small or large strings by reference in C#? I assumed transferring by value would force the runtime to create a clone of the input string, and thus be slower. Is it recommended for all string functions to transfer values by reference therefore?

Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

1 Answers1

11

I assumed transferring by value would force the runtime to create a clone of the input string, and thus be slower.

Your assumption is incorrect. String is a reference type - calling a method with a string argument just copies that reference, by value. There's no cloning involved. It's a fixed size - 4 or 8 bytes depending on which CLR you're using.

(Even if it were a value type, it would have to basically contain a reference to something else - it wouldn't make sense to have a variable-size value type allocated directly on the stack. How much space would be allocated for the variable? What would happen if you changed the value of the variable to a shorter or longer string?)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So what would be faster therefore `ref string a`, or `string a`?? – Robin Rodricks Sep 02 '12 at 07:55
  • 2
    @Geotarget: Probably just `string a` - but you shouldn't make the decision based on performance anyway, except in extreme corner cases with large value types (which are rarely a good idea). You should do it based on what semantics you want. – Jon Skeet Sep 02 '12 at 07:57
  • Assuming I'm transferring large strings around, what then? – Robin Rodricks Sep 02 '12 at 08:00
  • 1
    @Geotarget then no difference; even when passing a large string you are only actually passing a *reference*, regardless of whether that reference is by-ref or by-val – Marc Gravell Sep 02 '12 at 08:05
  • 1
    Correct. I've verified this by changing all `ref string`'s in a large project to plain `string` and there's no speed hit. – Robin Rodricks Sep 02 '12 at 08:14