I guess mutable globals don’t play well with BenchmarkTools. This is how I would do the benchmarking.
using BenchmarkTools, Dictionaries
const CI = CartesianIndex.([(0,1), (1,0), (0,-1), (-1,0)])
function arcipelago(a, cidx, dcidx)
i=1
c=findfirst(==(-1),dcidx)
while !isnothing(c)
cc=CartesianIndex{2}[]
ci=[c]
while !isempty(ci)
for j in ci
a[j]=i
dcidx[j]=1
for n in CI
x=j+n
if haskey(dcidx,x) && dcidx[x]==-1
dcidx[x]=0
push!(cc,x)
end
end
end
ci=cc
cc=CartesianIndex{2}[]
end
c=findfirst(==(-1),dcidx)
i+=1
end
a
end
A = rand([1, 0], 8, 10)
@btime arcipelago(a, cidx, dcidx) setup=(a=copy(A); cidx=findall(>(0),a); dcidx=Dictionary(cidx,fill(-1, length(cidx)))) evals=1
And to reiterate, all the timing artifacts are due to repeated calls where dcidx no longer is set to -1, findfirst(==(-1), dcidx) returns nothing and the while loop isn’t ever entered. You can add some debug prints to see it in action while running @btime.