WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Performance discrepancy between get! and haskey + setindex! #60310

@frankwswang

Description

@frankwswang

MWE (tested on Julia 1.12.2):

julia> function foo1(vs::AbstractVector{Int}, ks::AbstractVector{Int})
           d = Dict{Int, Int}()
           for (k, v) in zip(ks, vs)
               get!(d, k, v)
           end
           d
       end
foo1 (generic function with 1 method)

julia> function foo2(vs::AbstractVector{Int}, ks::AbstractVector{Int})
           d = Dict{Int, Int}()
           for (k, v) in zip(ks, vs)
               haskey(d, k) || setindex!(d, v, k)
           end
           d
       end
foo2 (generic function with 1 method)

julia> ks = rand(1:200, 1000);

julia> vs = rand(1:500, 1000);

julia> using BenchmarkTools

julia> @benchmark foo1($vs, $ks)
BenchmarkTools.Trial: 10000 samples with 6 evaluations per sample.
 Range (min  max):  4.733 μs   1.276 ms  ┊ GC (min  max):  0.00%  99.29%
 Time  (median):     6.750 μs              ┊ GC (median):     0.00%
 Time  (mean ± σ):   8.594 μs ± 26.948 μs  ┊ GC (mean ± σ):  15.13% ±  8.56%

  █▅▄▁ ▃▆▅▄▂▂▂▁▁▁▄▄▃▂▂▃▃▂▂▁▁▁   ▁▁                           ▂
  █████████████████████████████████▇▇█▆▇▆▅▇▆▆▅▅▄▅▄▅▄▁▄▄▄▄▄▁▃ █
  4.73 μs      Histogram: log(frequency) by time     23.5 μs <

 Memory estimate: 23.15 KiB, allocs estimate: 17.

julia> @benchmark foo2($vs, $ks)
BenchmarkTools.Trial: 10000 samples with 8 evaluations per sample.
 Range (min  max):  3.200 μs   1.442 ms  ┊ GC (min  max):  0.00%  99.50%
 Time  (median):     3.775 μs              ┊ GC (median):     0.00%
 Time  (mean ± σ):   6.035 μs ± 23.060 μs  ┊ GC (mean ± σ):  14.87% ±  8.71%

  █▅▄▄▃▁▁▅▅▂    ▁▄▄▄▃▁▁▁▁ ▁   ▁▁▁▁                           ▂
  ██████████████████████████▇████████▇▇▇▆▅▅▄▅▃▁▄▅▃▄▅▄▃▃▁▄▄▃▄ █
  3.2 μs       Histogram: log(frequency) by time       19 μs <

 Memory estimate: 23.17 KiB, allocs estimate: 17.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions