了解参考带宽

时间:2016-05-11 11:25:08

标签: java

我正在阅读Richard Warburton的一本关于java 8的书。在关于原始流的部分中,作者给出了关于原语与引用的一些解释(强调我的):

  

对于执行大量数值运算的算法,其成本为   装箱拆箱与 使用的额外内存带宽相结合    通过分配的盒装对象 可以使代码显着变慢。

带宽是多少?它是否被认为是原语,我们在内存中具有它们的实际值,并且可以直接使用它们。

对于引用,反过来,我们使用指向堆的指针,并在某个对象上调用方法,我们必须通过给定的指针执行间接,然后我们才能调用该方法。那被认为是带宽吗?

我们真的要担心实际带宽吗?

2 个答案:

答案 0 :(得分:3)

A realistic computer has a limitation on how quickly it can retrieve bytes/words from memory, with one faster speed for reading from CPU caches, and a slower speed for reading from memory that is not in the L1/L2/L3/... cache.

When we're working through a large primitive/boxed stream, we can assume that we don't have elements of the collection in the CPU cache, and they need to be fetched from main memory.

In a gross oversimplification applicable to OpenJDK, an object in memory will contain references to its java.lang.Class and all superclasses thereof (used for checking casts and related), followed by its fields. This can be fairly sizable, for example with the boxed java.lang.Integer where it would likely need to maintain a reference to Class<Integer> and Class<Number>. Needless to say, this is much larger than the 32 bits needed for a primitive.

When one is iterating/streaming a collection of Integers, it's necessary to load these objects into memory, and for simple numerical operations on the elements, the memory becomes the bottleneck.

答案 1 :(得分:2)

Basically yes. When dealing with boxed objects instead of primitives, you have reference overhead as well as object overhead. However that's not something that you should really be constantly thinking about.

Of course you want to be careful that you're using for example int[] instead of Integer[] if you don't need an object array, but there are usually far better places for optimization before you need to worry about primitive vs. boxed. In DB or network bound systems the CPU caches usually have very little saying in the final throughput of the application. In a CPU bound system this is naturally more relevant as explained in hexafraction's answer.