ThreadLocal变量的性能 [英] Performance of ThreadLocal variable

查看:589
本文介绍了ThreadLocal变量的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ThreadLocal 变量读取多少比常规字段慢?

How much is read from ThreadLocal variable slower than from regular field?

更具体地说,是简单的对象创建比访问 ThreadLocal 变量更快还是更慢?

More concretely is simple object creation faster or slower than access to ThreadLocal variable?

我认为它足够快以便 ThreadLocal< MessageDigest> 实例比每次创建 MessageDigest 的实例要快得多。但这是否也适用于字节[10]或字节[1000]?

I assume that it is fast enough so that having ThreadLocal<MessageDigest> instance is much faster then creating instance of MessageDigest every time. But does that also apply for byte[10] or byte[1000] for example?

编辑:问题是调用时真正发生的事情ThreadLocal 得到了什么?如果那只是一个字段,就像任何其他字段一样,那么答案就是它总是最快,对吗?

Question is what is really going on when calling ThreadLocal's get? If that is just a field, like any other, then answer would be "it's always fastest", right?

推荐答案

运行未发布基准测试, ThreadLocal.get 在我的机器上每次迭代大约需要35个周期。不是很多。在Sun的实现中, Thread 中的自定义线性探测哈希映射将 ThreadLocal 映射到值。因为它只能由一个线程访问,所以它可以非常快。

Running unpublished benchmarks, ThreadLocal.get takes around 35 cycle per iteration on my machine. Not a great deal. In Sun's implementation a custom linear probing hash map in Thread maps ThreadLocals to values. Because it is only ever accessed by a single thread, it can be very fast.

小对象的分配需要相似的周期数,尽管由于缓存耗尽,你可能会在紧密的循环中得到一些较低的数字。

Allocation of small objects take a similar number of cycles, although because of cache exhaustion you may get somewhat lower figures in a tight loop.

构建 MessageDigest 可能相对昂贵。它有相当数量的州和建设通过提供商 SPI机制。您可以通过克隆或提供提供商进行优化。

Construction of MessageDigest is likely to be relatively expensive. It has a fair amount of state and construction goes through the Provider SPI mechanism. You may be able to optimise by, for instance, cloning or providing the Provider.

仅仅因为它可能是更快地缓存在 ThreadLocal 而不是创建并不一定意味着系统性能会提高。您将获得与GC相关的额外开销,这会减慢所有内容。

Just because it may be faster to cache in a ThreadLocal rather than create does not necessarily mean that the system performance will increase. You will have additional overheads related to GC which slows everything down.

除非您的应用程序非常大量地使用 MessageDigest ,否则我想考虑使用传统的线程安全缓存。

Unless your application very heavily uses MessageDigest you might want to consider using a conventional thread-safe cache instead.

这篇关于ThreadLocal变量的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆