Is there any preference between `iszero` and `==0` for simple numbers?

I noticed that there are functions like iszero that are meant for arrays, but also work on integers. When writing Julia code, is it preferred Julia “style” to use iszero for checking whether an integer is equal to zero, or is it better to just use == 0?

For example if I was checking if an Int is divisible by another Int, I could do:

if n % z == 0

or:

if iszero(n % z)

Is there a convention in Julia for which should be used? And, is there any performance difference between the two?

I’d be surprised if there was a performance difference because:

julia> @which iszero(1)
iszero(x) in Base at number.jl:42

and

The advantage over == 0 is of course that your code becomes type generic, as isszero tests against zero(x), which is not always 0 (i.e. integer zero):

julia> zero(Complex)
0 + 0im

but you could of course do == zero(x) instead of == 0 yourself.

3 Likes

I use iszero to let testing for zero stand out from other comparisons.

I think using n == 0 is fine when you know for sure that n is an ordinary (and perhaps real) number. You know this because it’s an internal variable, or there is a type constraing on an input variable, for example.

iszero(x) is better when you don’t have full control over the type of x, or if it’s not an ordinary number, otherwise it seems a bit like overkill to me (though a pretty gentle overkill at that.)

1 Like