Skip to content

Instantly share code, notes, and snippets.

@284km
Last active May 27, 2021 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 284km/ce7fd9b35d05000ad960acaa43c1f446 to your computer and use it in GitHub Desktop.
Save 284km/ce7fd9b35d05000ad960acaa43c1f446 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
ARRAY = [1, 2, 3, 1]
def fast
ARRAY.uniq!
end
def slow
ARRAY.uniq.length != ARRAY.length
end
Benchmark.ips do |x|
x.report('uniq!') { fast }
x.report('uniq.length') { slow }
x.compare!
end
__END__
Warming up --------------------------------------
uniq! 666.486k i/100ms
uniq.length 466.625k i/100ms
Calculating -------------------------------------
uniq! 6.596M (± 2.9%) i/s - 33.324M in 5.056745s
uniq.length 4.654M (± 1.5%) i/s - 23.331M in 5.014560s
Comparison:
uniq!: 6596204.0 i/s
uniq.length: 4653775.4 i/s - 1.42x (± 0.00) slower
$ ruby -v
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-darwin19]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment