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?
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With