0

When declaring a byte in Java, you need less memory space than declaring an integer. So is it more efficient (e.g. by using less memory), to iterate through e.g. an array by using a byte, when e.g. the array length < 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++) {}
1

2 Answers 2

3

No. Write the clearest, most intuitive code you can. The JVM will shine the most in the common use cases.

If you are Concerned about writing efficient code, look to your algorithms and read books on efficient java.

Sign up to request clarification or add additional context in comments.

Comments

2

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 < array.length and b < array.length generates the exact same code.

However, the code for i++ and b++ is quite different. 1 bytecode instruction for an int, 5 bytecode instructions for a byte.

What JIT does with that is unknown, but if anything, using byte as the array iterator variable makes the code slower.

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.

1 Comment

Hotspot can be tickled to tell what it generates. I haven’t played with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.