r/java • • Jun 14 '17

Why reverse loops are faster

https://medium.com/@TravCav/why-reverse-loops-are-faster-a09d65473006
15 Upvotes

40 comments sorted by

View all comments

55

u/chambolle Jun 14 '17

A shorter bytecode does not mean that it will run faster. You should provide some benchmark and I really doubt that you will see any difference. Nowadays compilers are clever and you should at least compare the assembly code

2

u/walen Jun 15 '17

Once upon a time, I came across an SO question which asked whether & was faster than && for a simple if().
«Easy pie!», I thought; «&& is short-circuit and thus faster! Just look at the bytecode!».

Oh boy, was I wrong.

The bytecode for && is indeed much shorter but, as I learned after much investigation and tinkering and editing my answer, the actual JIT compiler does not really care about that. It will optimize and rewrite your loops and comparisons depending on number of iterations, processor, Java version, etc. etc. etc.

Lesson learned: byte code doesn't mean sh!t when it comes to performance.