Understanding performance using `@btime` and `@code_warntype`, `@code_llvm`, etc

String interpolation (used here) forces the allocation of the gcframe. There’s a standard trick for avoiding this problem: instead of

function mysqrt(x)
    x >= 0 || throw(ArgumentError("x must be positive, got $x"))
    sqrt(x)
end

do something like this:

function mysqrt(x)
    nonpos(x) = throw(ArgumentError("x must be positive, got $x"))
    x >= 0 || nonpos(x)
    sqrt(x)
end

By putting the error message generation in a separate function you ensure the gcframe gets allocated only in the error condition. In other people’s code (esp. older code) you may sometimes see @noinline in front of nonpos, because of course this trick fails if nonpos gets inlined into mysqrt; however, from 0.7 julia’s compiler is smart enough to figure that out on its own.

10 Likes