Are exceptions in Julia "Zero Cost"

It would be interesting to see what you tried. The test is, of course, not zero-cost: you still have to execute the condition to see if the exception should be triggered. I’m not seeing any difference, although there is some inconsistency in the @btime results:

function f(n::Int)
    x = rand(Int)
    t = 0
    try
        for i = 1:n
            i == x && error("bad i value")
            t += i
        end
    catch
    end
    return t
end

function g(n::Int)
    x = rand(Int)
    t = 0
    for i = 1:n
        i == x && break
        t += i
    end
    return t
end

and timings:

julia> using BenchmarkTools

julia> @btime f(10_000)
  4.541 μs (0 allocations: 0 bytes)
50005000

julia> @btime g(10_000)
  2.296 μs (0 allocations: 0 bytes)
50005000

julia> @btime g(10_000)
  4.517 μs (0 allocations: 0 bytes)
50005000

julia> @btime f(10_000)
  4.540 μs (0 allocations: 0 bytes)
50005000

julia> @btime g(10_000)
  4.516 μs (0 allocations: 0 bytes)
50005000

julia> @btime f(10_000)
  4.540 μs (0 allocations: 0 bytes)
50005000

There’s that one @btime for g(10_000) that’s 2.296 μs but I’ve seen that for f(10_000) as well, although far less often. Could be something to do with the branch predictor.

2 Likes