什么时候应该使用原语而不是包装对象? [英] When should I use primitives instead of wrapping objects?
问题描述
实际上此处是类似的主题,几乎没有实用价值.据我了解,原语性能更好,除需要与对象相关的功能(例如 null
检查)的情况外,应在所有地方使用.对吧?
Actually here is a similar topic with little practical value.
As far as I understand, primitives perform better and should be used everywhere except for the cases where Object-related features (e.g. null
check) are needed. Right?
推荐答案
不要忘记这一点,因为为每次装箱创建新包装都非常昂贵,尤其是考虑到通常在方法的单个作用域中使用它,<一个href ="http://chaoticjava.com/posts/autoboxing-tips/" rel ="nofollow noreferrer">自动装箱使用了一组普通包装器.
Do not forget that, since creating a new wrapper for every boxing occurrence is quite expensive, especially considering it usually being used at a single scope of a method, Autoboxing uses a pool of common wrappers.
This is in fact an implementation of the flyweight design pattern. When a boxing occurs for a well-known value, instead of creating a new wrapper instance, a pre-created instance is fetched from a pool and returned.
一个后果是:仍然不建议使用自动装箱进行科学计算.例如,代码d = a * b + c使用a,b,c和d的Integer类,并且生成的代码是d.valueOf(a.intValue()* b.intValue()+ c.intValue()).所有这些方法调用都有其自身的开销,因此通常建议在需要将原语存储在集合中时使用自动装箱.
One consequence is: it’s still not recommended to use autoboxing for scientific calculations. For example, the code d = a * b + c is using Integer classes for a, b, c and d, and the generated code is d.valueOf(a.intValue() * b.intValue() + c.intValue()). All these method invocations have their own overhead, so it’s usually recommended to use autoboxing when needed to store primitives in collections.
即使这样,如果您有一个大量的包装整数,则开销可能意味着更长的执行时间,最多可达 20倍,如本文报道.
And even then, if you have a huge collection of Integer wrapping int, the overhead can implies longer execution times, up to 20 times longer, as reported in this article.
Jb添加了以下重要评论:
Jb adds this important comment:
也Wrapper.valueOf(primitive)使用包装池.因此,最好将Integer.valueOf(5)替换为新的Integer(5)
Also Wrapper.valueOf(primitive) uses pool of wrappers. So prefer Integer.valueOf(5) to new Integer(5)
这篇关于什么时候应该使用原语而不是包装对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!