Number 类的性能
我只是想知道 Number 类的性能,而不是使用泛型甚至大量函数来处理原始类型。
原始类型显然是我认为最快的选择,但是如果性能影响不是太大,编码器可能更容易只使用 Number 类或泛型,而不是创建一个接受并返回 long 的函数,双(等)。
我即将对提到的 3 个选项进行性能基准测试。这样做时我应该注意/尝试什么,或者更好的是,之前有人这样做过,他们可以给我结果吗?
I'm just wondering about the performance of the Number class as opposed to, say using generics or even a whole lot of functions to handle primitive types.
The primitive types would clearly be the fastest option I would assume, however if the performance hit is not too huge, it would likely be easier for the coder to just use the Number class or generics rather than making a function that accepts and returns long, double (etc).
I am about to do a performance benchmark of the 3 options mentioned. Is there anything I should be aware of/try out when doing this, or even better, has someone done this before that they can give me results to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,您使用 Number 类而不是基本类型,因为您需要在集合或基于对象的其他类中使用这些值。如果您不受此要求的限制,那么您应该使用原语。
Typically you use the Number class as opposed to primitive types because you need to use these values in collections or other classes that are based on Objects. If you are not restricted by this requirement, then you should use primitives.
是的,与 int、long 等基本类型相比,使用 Number 类会降低性能。特别是如果您要创建大量新的 Number,与创建基本类型相比,您会需要担心性能类型。但将数字传递给方法时不一定是这种情况。将 Number 实例传递给方法并不比传递 int 或 long 慢,因为编译器基本上可以传递指向内存位置的“指针”。这是非常笼统的信息,因为您的问题非常笼统。
Yes, there is a performance hit associated with using the Number class, in comparison with primitive types like int, long, etc. Especially if you are creating a lot of new Numbers, you will want to worry about the performance when compared with creating primitive types. But this is not necessarily the case for passing Numbers to methods. Passing an instance of Number to a method is no slower than passing an int or a long, since the compiler can basically pass a "pointer" to a memory location. This is very general information because your question is very general.
您应该注意的一件事是,当您使用 Numbers 时,对象分配可能是最大的成本。这会影响您的基准测试,因为使用自动装箱的某些操作可以使用缓存值(不会创建对象),并且可以为您提供更好的性能结果。例如,如果您使用 -128 到 127 之间的整数,您将获得比 -128 到 127 之间的双精度数更好的结果,因为前者使用缓存值,后者则不缓存值。
简而言之,如果您要对 Numbers 的使用进行微基准测试,则需要确保您使用的值的范围是现实的,并非所有值在性能方面都是相同的(当然对于基元来说这并不重要)
One thing you should be aware is that object allocation is likely to be the largest cost when you use Numbers. This affects your benchmarks as certain operations which use auto-boxing can use cached values (which don't create objects) and can give you much better performance results. e.g. if you use Integers between -128 and 127, you will get much better results than Doubles from -128 to 127 because the former uses caches values, the later does not.
In short, if you are micro-benchmarking the use of Numbers, you need to ensure the range of values you use are realistic, not all values are equal in terms of performance (of course for primitives this doesn't matter so much)