I saw some people wrote this Boolean equal in their code, I usually put constant at the right hand side of "==" operator. I notice 0 == a has faster operation than a == 0. Can someone explain why? And what's the best practice for it?
It's a relic of the C/C++ world.
In C, the advantage of writing 0 == a
vs. a == 0
is that you can't accidentally write a = 0
instead, which means something entirely different. Since 0
is an rvalue, 0 = a
is illegal.
In Java that reasoning does not apply because a = 0
is illegal as well (since 0
is not boolean, a
can't be boolean). It doesn't hurt though, so it really doesn't matter a lot which one to choose.
Performance has absolutely nothing to do with that.