❯ ruby --version
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-darwin21]
❯ ruby main.rb
user system total real
Set 0.231883 0.015556 0.247439 ( 0.247975)
Array (symbol) 0.500424 0.042862 0.543286 ( 0.544288)
Array#sort (symbol) 4.076750 0.031886 4.108636 ( 4.121614)
Array (string) 0.555537 0.090037 0.645574 ( 0.656218)
Array#sort 3.354656 0.117255 3.471911 ( 3.613801)
Last active
December 22, 2021 11:48
-
-
Save yammmt/35dd490cd238824059ee1b7ebe1614e7 to your computer and use it in GitHub Desktop.
Benchmark of Ruby `Set`/`Array`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
require 'set' | |
ARRAY_SIZE = 1_000_000 | |
a_values = (0..ARRAY_SIZE).to_a.shuffle | |
b_values = (0..ARRAY_SIZE).to_a.shuffle | |
Benchmark.bm 20 do |r| | |
s = Set.new | |
r.report "Set" do | |
ARRAY_SIZE.times do |i| | |
s.add(a_values[i] * 100_000_000 + b_values[i]) | |
end | |
end | |
arr_i = Array.new | |
r.report "Array (symbol)" do | |
s.each do |ss| | |
arr_i.push( | |
a: ss / 100_000_000, | |
b: ss % 100_000_000, | |
) | |
end | |
end | |
r.report "Array#sort (symbol)" do | |
arr_i.sort_by { |a| [a[:a], a[:b]] } | |
end | |
arr_s = Array.new | |
r.report "Array (string)" do | |
s.each do |ss| | |
arr_i.push( | |
'a': ss / 100_000_000, | |
'b': ss % 100_000_000, | |
) | |
end | |
end | |
r.report "Array#sort" do | |
arr_i.sort_by { |a| [a['a'], a['b']] } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment