Skip to content

Use sizehint! when creating Dict from Generator #36334

@nacnudus

Description

@nacnudus

Dictionaries can be created from generator expressions, but don't seem to use sizehint!. This could give better performance.

I couldn't confirm this in the source code, so I asked on discourse where a benchmark showed fewer allocations when manually calling sizehint! than when using a generator expression.

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    collectionsData structures holding multiple items, e.g. setsperformanceMust go faster

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions