Do comprehensions implicitly use sizehint?

You can test it:

using BenchmarkTools

println("Implicit:")
@btime begin
    dict = Dict(string(i) => sind(i) for i = 0:5:360)
end

println("Explicit:")
@btime begin
    dict = Dict{String, Int}()
    sizehint!(dict, 360÷5)
    for i in 0:5:360
        dict[string(i)] = i
    end
end

Results in:

Implicit:
  8.669 μs (156 allocations: 13.42 KiB)
Explicit:
  5.737 μs (153 allocations: 9.70 KiB)

So it appears that the first does not use sizehint! since it ends up with a few more allocations.

6 Likes