Why Builtin Dict `ht_keyindex` use & rather than %?

I was reading the implementation of Dict, I don’t know why ht_keyindex use (index & (sz-1)) + 1 rather than index % sz + 1, won’t the compiler optimize it? I use BenchmarkTools to check whether the previous implementation is faster, and it is a little bit faster indeed. But I would like to know why this is faster.

I tested this on Julia v0.6.3.

The compiler can only optimize it if it could prove they are equivalent. Since sz is an arbitrary number, the compiler can’t know that it’s always actually a power-of-two number.

2 Likes