# frozen_string_literal: true
require 'bundler/setup'
Bundler.setup :system
require 'pry-byebug'
require 'benchmark'
require 'benchmark/ips'
require 'benchmark/memory'
puts '```ruby'
puts File.read(__FILE__).gsub("\t", ' ')
puts '```'
puts
puts '### Output'
puts
puts '```'
ARRAY = %w[1 1 2 3 4 4 4].freeze
def via_union
ARRAY | []
end
def via_uniq
ARRAY.uniq
end
def test
results = %i[
via_union
via_uniq
].each_with_object([]) do |method_name, array|
array << (result = send method_name)
puts "Result of #{method_name}:"
pp result
puts
end
uniq_size = results.uniq.size
puts "Uniq results: #{uniq_size}"
puts
exit 1 if uniq_size > 1
end
test
Benchmark.ips do |x|
x.report('via_union') { via_union }
x.report('via_uniq') { via_uniq }
x.compare!
end
Benchmark.memory do |x|
x.report('via_union') { 100.times { via_union } }
x.report('via_uniq') { 100.times { via_uniq } }
x.compare!
end
puts '```'
Result of via_union:
["1", "2", "3", "4"]
Result of via_uniq:
["1", "2", "3", "4"]
Uniq results: 1
Warming up --------------------------------------
via_union 229.711k i/100ms
via_uniq 364.966k i/100ms
Calculating -------------------------------------
via_union 2.308M (± 1.2%) i/s - 11.715M in 5.077271s
via_uniq 3.582M (± 1.3%) i/s - 18.248M in 5.095760s
Comparison:
via_uniq: 3581676.4 i/s
via_union: 2307703.0 i/s - 1.55x (± 0.00) slower
Calculating -------------------------------------
via_union 24.000k memsize ( 0.000 retained)
200.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
via_uniq 7.200k memsize ( 0.000 retained)
100.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
Comparison:
via_uniq: 7200 allocated
via_union: 24000 allocated - 3.33x more