views:

93

answers:

1

I am currently reading C# in Depth by Jon Skeet and have been reading about value and reference types.

It got me thinking about the cost of using value types as method parameters due to that value being copied when passed. While this cost is not much when considering integers, what if those value parameters were strings which got passed around numerous times.

Would there be a benefit to using say a StringBuilder class and passing it instead of a string type?

If you considered that the string was long, say 1024 characters, and was passed around even just a few times between methods, contrast that with a StringBuilder with the same value which would end up passing the value of the reference being 4 or 8 bytes each time, you could have a considerable performance inprovement.

This question may also highlight a vital piece of understanding I may be missing regarding the String type, feel free to point this out where required.

Also, what what impact would this have on garbage collection regarding the strings in each instance?

Edit: Apparently I did forget one vital piece of information about strings which renders the question null and void. Thanks grover.

+7  A: 

String is not a value type, they're just immutable objects.

Passing a string around incurs the same cost as any other object: The size of its reference, which is 4 bytes on Win32.

On additional note: The value type semantics (by value passing) can be implemented by the compiler in an optimized way. I haven't looked at how the MS JIT is doing it, but it certainly can still send only a pointer to it and require the target to make a copy on write.

This is what we're going to do in the Managed Operating System Alliance JIT/AOT compiler.

__grover