tags:

views:

94

answers:

3

I've been reading a bit about immutable structures such as string. Simply put, they don't change state once they've been created (so for instance asking for a substring gives you a new string).

Now, I was wondering whether the CLR "knows" that a certain type is immutable, and uses this fact to do something clever at runtime, or is immutability mainly something that makes certain scenarios simpler to program?

+5  A: 

In general the CLR doesn't do anything special with immutable types. They are treated in the same way as any other types.

For strings there is special support. Strings can be interned and reused. In C#, source code string literals are automatically interned by the compiler. You can also intern a string yourself by calling String.Intern.

Mark Byers
String literals are interned by the compiler, not by the CLR. It's possible to produce IL with multiple copies of the same string (just a bad idea for a compiler to do so).
Jon Hanna
@Jon Hanna: +1 - Yes, that's right. I've updated my post to make that point more clear. Thanks.
Mark Byers
It's a bit of a nit-pick, but since the querant says the CLR, maybe they care about that rather than the compiler, or else I'd have said nothing. There are times when pedantry helps one be a good coder, times when it just makes one an annoying pedant. Hopefully this was the former :)
Jon Hanna
A: 

In the CLR's perspective the value IS MUTABLE. For example : the CLR can change the object's data to perform caching. The users of the structure can't change it's value, but the CLR can do it in several scenarios. That's why the CLR can't enforce the immutability on itself and can't relay on it during the runtime.

Adibe7
+2  A: 

Potentially, it could be possible for the compiler (rather than the CLR) to do something clever with it in producing IL. I don't know if it does, and honestly don't care: If it doesn't maybe it will in the future (later versions). If it does, maybe it won't in the future (an edge-case is found showing the optimisation to be ill-advised.

I'm happy to think "well, if this is readonly then maybe the compiler (or indeed, the CLR) will do something clever with it, so that'll be a free improvement". It'll be a free improvement because I'm never going to make something readonly to take advantage of such optimisations even if I learn that it definitely does so and that such savings are great. I will only ever make something readonly if it makes sense to be readonly. I do this a lot because my style favours heavy use of immutable objects, but I will only do it because the object is logically immutable, rather than make it immutable in pursuit of some optimisation and then have to workaround the immutability.

Of course, there are also certain ways that you can be clever with immutable objects (in particular, when working out the effects of different multi-threaded scenarios will have on your code).

Jon Hanna