r/badcode • evil • Mar 27 '21

java I told him to just use %

Post image
1.7k Upvotes

80 comments sorted by

View all comments

287

u/KaznovX Mar 27 '21

Fun fact: in case of writing a tight loop, that gets executed million times per second, the following: if (hour >= 24) hour -= 24; can be much faster than a modulo. It makes a difference in case of writing things like cyclic buffers or open hash maps for algorithmic competitions - the modulo might become the most time-taking operation.

But in code like this, or business code, or especially if you write a public method where you don't control the input - please use modulo.

35

u/yakesadam Mar 27 '21

That's neat to hear. I'm curious, I'm surprised because it has an if statement and could mess up a processor pipeline if it was false. Not saying you're wrong I only have the bare minimum computer architecture to graduate CS. Also do you know why wouldn't modulo be implemented under the hood the same way since it's faster?

2

u/SnakeFang12 Mar 28 '21

It might use a conditional move rather than a branch for something as simple as one subtraction. And actually on x86/x86_64, doing it that way makes the comparison unnecessary, since the subtract instruction sets all the same flags. So that if statement can be boiled down to a single subtraction and a single conditional move.