Skip to content

Instantly share code, notes, and snippets.

@jodosha
Last active October 13, 2022 05:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jodosha/7fb02d74173f05673a72af479488dcae to your computer and use it in GitHub Desktop.
Save jodosha/7fb02d74173f05673a72af479488dcae to your computer and use it in GitHub Desktop.
Ruby benchmark: Array#uniq vs Set#to_a
#!/usr/bin/env ruby
require "benchmark/ips"
require "set"
INPUT = 100.times.map { "my-test-string" }.freeze
Benchmark.ips do |x|
x.report("Array#uniq") { INPUT.uniq }
x.report("Set#to_a") { Set.new(INPUT).to_a }
x.compare!
end
__END__
# I've omitted frozen string literal because the app under testing doesn't use it AND `Set#initialize` freezes strings.
# I wanted to reproduce the cost of freezing the strings in a scenario where they aren't frozen by default.
#
# > When a string is to be stored, a frozen copy of the string is stored instead unless the original string is already frozen.
# See: https://ruby-doc.org/stdlib/libdoc/set/rdoc/Set.html
Result:
Warming up --------------------------------------
Array#uniq 13.739k i/100ms
Set#to_a 5.406k i/100ms
Calculating -------------------------------------
Array#uniq 146.702k (± 3.2%) i/s - 741.906k in 5.063030s
Set#to_a 55.793k (± 4.0%) i/s - 281.112k in 5.047296s
Comparison:
Array#uniq: 146702.0 i/s
Set#to_a: 55793.0 i/s - 2.63x slower
Ruby:
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin16]
Hardware:
Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro12,1
Processor Name: Intel Core i7
Processor Speed: 3,1 GHz
Number of Processors: 1
Total Number of Cores: 2
L2 Cache (per Core): 256 KB
L3 Cache: 4 MB
Memory: 16 GB
Boot ROM Version: 184.0.0.0.0
SMC Version (system): 2.28f7
Software:
System Software Overview:
System Version: macOS 10.12.6 (16G2016)
Kernel Version: Darwin 16.7.0
Time since boot: 16 days 22:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment