Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it faster to transfer strings by reference between functions?

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?

like image 995
Robin Rodricks Avatar asked Dec 20 '22 16:12

Robin Rodricks


1 Answers

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?)

like image 86
Jon Skeet Avatar answered Dec 30 '22 09:12

Jon Skeet