开发者

ThreadStatic vs. ThreadLocal<T> Performance: speedups or alternatives?

开发者 https://www.devze.com 2023-01-18 08:59 出处:网络
I recently read this post about poor performance of fields marked T开发者_如何转开发hreadStatic - they\'re apparently 60x slower than normal field access. Does .NET 4\'s ThreadLocal< T > perform an

I recently read this post about poor performance of fields marked T开发者_如何转开发hreadStatic - 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?


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.


They say that [ThreadStatic] is much more performant than Thread.AllocateDataSlot.

The implementation of ThreadLocal<T> (according to Reflector) has 16 dedicated types that just use [ThreadStatic] under the cover. Once they are used up and not freed, TheadLocal<T> switches over to Thread.AllocateDataSlot. (Actually it seems to be 16^3 slots per <T>, they do a very funny scheme of creating generic types to hold the slots)

So I guess [ThreadStatic] is the fastest.

Remember to always check for leaky abstractions and look at the implementation! Never prematurely skip optimizations like that ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消