Is the compiler smart enough to remove this duplicate computation?

I don’t think it will, since there’s no guarantee that diff doesn’t modify w. Also, an array could be modified from some other thread. The output of @code_llvm and @code_native are much too long for me to be able to parse.

You should avoid this pattern in most cases:

all(f.(diff(w; dims=3)))

and instead do

all(f, diff(w; dims=3))

The first creates an unnecessary array allocation, and also calculates f for all inputs, even when it could bail out early.

I would just write:

function bar(w)
    @assert all(x->(x>0 | isnan(x)), diff(w; dims=3)) "Something's amiss."
end

BTW, you should be aware of when to use @assert (from the docstring):

 │ Warning
 │
 │  An assert might be disabled at various optimization levels. Assert should therefore only be used as a debugging tool and not used for authentication verification
 │  (e.g., verifying passwords), nor should side effects needed for the function to work correctly be used inside of asserts.

Unless you are aware of this already, it’s likely that you should throw an error instead.

8 Likes