Get the latest tech news
Identifying Leap Years (2020)
One of my colleagues was recently looking at some date-based calculations that needed to know whether a year is a leap year or not, on the hot path, and he found an 8% speed improvement by reworking the leap year predicate a bit. The JVM compiles this down to a few fast integer operations, avoiding slow things like division entirely. I thought it’d be interesting to dig into how to calculate the leap year predicate without division.
Note that your compiler may already do these optimisation steps for you, so I don’t recommend obfuscating your leap-year predicate implementation like this without some careful contemplation of its worth. I looked at what GCC does with the naive calculation when compiling to AVR assembler (as used by Arduino microcontrollers) and it came up with something much slower than this even with-O2. The divisibility check mentioned above is quite a general thing that really only needs the divisor to be coprime to the modulus.
Or read this on Hacker News