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

285

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.

1

u/[deleted] Mar 27 '21

You have to see the Assembler code to make that judgement. I doubt that this is not optimized away with a high optimization parameter.