views:

34

answers:

2

I recently read this post about poor performance of fields marked ThreadStatic - they're apparently 60x slower than normal field access. Does .NET 4's ThreadLocal< T > perform any better?

Are there any alternatives that offer high performance thread-specific storage?

+1  A: 

Unless you have a specific performance problem, forget about it.

Only worry about optimization when your app is running slower than required; at that point you are at a stage where you have enough information to make an informed decision about what should be optimized.

Optimization before it's required is a waste of time because there is a very good chance it won't ever be a problem.

clocKwize
Usually an appropriate angle... I *should* have mentioned that I'm writting an extensible dependency injection container which is intended to make calling code very readable, testable and maintainable. To enable thread-affined factories and singletons, an efficient means of resolving a factory for the current thread is needed. This being a universally usable pattern, I'd like to make it every bit as performant as possible, since it will affect all calling code.
Mark
you'd like to make it as performant as possible... why? 60x slower than an immeasurably fast operation is still immeasurably fast :) You and wasting time trying to optimise something that 99 times out of 10 won't be the thing slowing your code down.
clocKwize
+1  A: 

Bear in mind that that was in 2008 - I believe that .NET 4 is a lot faster for ThreadStatic fields than .NET 3.5 was. I can't remember for sure, but you could run tests if you want.

That said, I'm not really convinced by the test description - because it's unrealistic. Do you really need to repeatedly read a thread-local field in a loop? Isn't it more likely that you'll read it once, and then once a bit later on in a different bit of code?

Ultimately, the real question is whether either or both of these approaches performs well enough for your particular requirement. I prefer ThreadLocal<T> to ThreadStatic not for performance reasons, but because it allows for appropriate initialization - see my article on randomness for an example.

Jon Skeet
Great article on random, and thanks for the answer Jon. I've ended up going with ThreadLocal simply because it's way smarter (and instance-safe) compared to ThreadStatic.
Mark
@Mark: Exactly - it's much nicer :)
Jon Skeet