Pergunta

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?

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top