Is it faster to pass strings by reference between functions?

Is it better to pass small or large lines by reference in C #? I suggested that wrapping by value will force the runtime to create a clone of the input string and therefore will be slower. Is it recommended to pass values ​​by reference for all string functions?

+4
source share
1 answer

I assumed that passing by value will force the runtime to create a clone of the input string and therefore will be slower.

Your guess is wrong. String is a reference type - a method call with a string argument simply copies this reference by value. There was no cloning. This is a fixed size - 4 or 8 bytes, depending on which CLR you are using.

(Even if it were a value type, it would basically contain a reference to something else - it would be pointless to have a variable value type allocated directly on the stack. How much space will be allocated for the variable? What happens if you change the value of the variable to a shorter or longer string?)

+11
source

All Articles