简体   繁体   English

在迭代循环中使用字节是否更有效?

[英]Is using byte in an iteration loop more efficient?

When declaring a byte in Java, you need less memory space than declaring an integer.在 Java 中声明一个字节时,与声明 integer 相比,您需要更少的 memory 空间。 So is it more efficient (eg by using less memory), to iterate through eg an array by using a byte, when eg the array length < 128?那么,当数组长度<128 时,使用字节来遍历数组是否更有效(例如,通过使用更少的内存)?

And if it is more efficient, are there any examples when I would really recognize improvements as a user?如果它更有效,是否有任何例子让我真正认识到作为用户的改进?

for(byte b = 0; b < array.length; b++) {}

instead of代替

for(int i = 0; i < array.length; i++) {}

No. Write the clearest, most intuitive code you can.不。尽可能写出最清晰、最直观的代码。 The JVM will shine the most in the common use cases. JVM 在常见用例中表现最为出色。

If you are Concerned about writing efficient code, look to your algorithms and read books on efficient java.如果您担心编写高效代码,请查看您的算法并阅读有关高效 java 的书籍。

Well, let's look at what the compiler generates.好吧,让我们看看编译器生成了什么。

Source code源代码

short[] array = new short[0];

for(int i = 0; i < array.length; i++) {}
for(byte b = 0; b < array.length; b++) {}

Byte code字节码

 0: iconst_0                      array = new short[0];
 1: newarray       short
 3: astore_1
-------------------------------------------------------
 4: iconst_0                      i = 0
 5: istore_2

 6: goto          12

 9: iinc          2, 1            i++

12: iload_2                       i < array.length
13: aload_1
14: arraylength
15: if_icmplt     9
-------------------------------------------------------
18: iconst_0                      b = 0
19: istore_2

20: goto          28

23: iload_2                       b++
24: iconst_1
25: iadd
26: i2b
27: istore_2

28: iload_2                       b < array.length
29: aload_1
30: arraylength
31: if_icmplt     23
-------------------------------------------------------
34: return

i = 0 and b = 0 generates the exact same code. i = 0b = 0生成完全相同的代码。

i < array.length and b < array.length generates the exact same code. i < array.lengthb < array.length生成完全相同的代码。

However, the code for i++ and b++ is quite different.但是, i++b++的代码完全不同。 1 bytecode instruction for an int , 5 bytecode instructions for a byte .一个int的 1 个字节码指令,一个byte的 5 个字节码指令。

What JIT does with that is unknown, but if anything, using byte as the array iterator variable makes the code slower. JIT 对此做了什么尚不清楚,但如果有的话,使用byte作为数组迭代器变量会使代码变慢。

Though, as others have already said, you very likely will not be able to tell the difference, especially relative to what is going on inside the loop (which in reality wouldn't be blank).但是,正如其他人已经说过的那样,您很可能无法区分差异,尤其是相对于循环内部发生的事情(实际上这不会是空白的)。

Write the code that makes sense for the code logic.编写对代码逻辑有意义的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM