Do comprehensions implicitly use sizehint?

The Wikibook on creating dictionaries gives an example that uses a comprehension. Would Julia automatically use a sizehint based on the size of for i = 0:5:360? Or would it be better to do that explicitly by creating an empty dictionary, then using sizehint, and then a for loop?

julia> dict = Dict(string(i) => sind(i) for i = 0:5:360)
Dict{String,Float64} with 73 entries:
 "320" => -0.642788
 "65"  => 0.906308
 "155" => 0.422618
 ⋮     => ⋮

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

Perhaps this could be improved by the Dict constructor with a generator using the IteratorSize trait, similar to collect.

I could not find an existing issue, please consider opening one.

2 Likes

Thanks, I’ve opened this issue https://github.com/JuliaLang/julia/issues/36334

2 Likes