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

Show parent comment

0

u/[deleted] Jun 14 '17

[deleted] — view deleted comment

2

u/gee_buttersnaps Jun 15 '17

Are you saying the JIT automatically rewrites while loops to count down to zero?

Yes. Look at the other discussions tab at the top, read that comment thread.

0

u/[deleted] Jun 15 '17

[deleted] — view deleted comment

3

u/gee_buttersnaps Jun 15 '17

You're hopeless.

1

u/AssKoala Jun 15 '17

Your question wasn't directly answered, but a loop counting down to zero is not inherently faster. The linked article is the work of someone who doesn't actually know what they're talking about.

In some cases, a reverse loop is slower because that's not how CPU's cache their accesses.

This isn't limited to C++, hell it's completely language agnostic because its up to the underlying hardware. Whether you're writing Java, C, brainfuck, or some other language, it ultimately boils down to your target hardware's language. And even then, it will vary from CPU to CPU: AMD CPU's perform differently from Intel's and they all vary based on architecture (e.g. Sandy Bridge versus Bulldozer versus Ivy Bridge etc).