Iterate over all byte values ​​-128-127 without casting in Java

I need to repeat all byte values ​​(from -128 to 127 inclusive). I could use an int iterator, but then I have to throw a byte every time. Using the byte iterator has a problem that I cannot check for b < 128 , as it will overflow. I thought about using a while loop and doing the test before incrementing, which is my best solution. Is there a better approach?

+6
source share
2 answers

Java bytes are signed so that they range from -128 to 127. In any case, you should not worry about ghosts and extra checks, because they are trivial to optimize. In fact, there is no such thing as a byte variable at the JVM level. It was still considered int.

+10
source

Using a byte iterator has a problem that I cannot verify for b <128

Check condition b == 127 for a loop termination condition.

However, I agree with antimony that it probably doesn't matter if you use int or byte in terms of performance. At the bytecode level, the JVM provides only 32 and 64-bit integer arithmetic operators.

At the language level, I think the type will happen in the case of byte , as well as in the case of int . Consider b++ actually equivalent

  byte b = ...; b = (byte) (b + 1); 

and that typecast is not noop because b + 1 creates an int value. So,

  for (byte b = -128; b != 127; b++) { ... } 

has a conditional type in it. Regardless of whether it means anything in terms of performance, it is controversial because JIT does a great job of optimizing unnecessary operations when generating native code.


Finally, the standard points about micro-optimization in Java:

  • If you haven’t profiled the code yet, there’s a good chance that you are wasting your time setting up something that doesn't matter.
  • You should rely on actual measurements (i.e. comparing YOUR application), and not on intuition or advice on which is faster. Be prepared for your intuition to be wrong.
  • Even if you manage to achieve noticeable acceleration due to micro-optimization, be careful that the acceleration is likely to be platform specific. Indeed, an improvement on one platform may be a slowdown on another platform.
+3
source

Source: https://habr.com/ru/post/919367/


All Articles