Skip to content

Instantly share code, notes, and snippets.

@wils3005
Created September 21, 2018 13:27
Show Gist options
  • Save wils3005/069e5caae36a55f640093f2426a00aac to your computer and use it in GitHub Desktop.
Save wils3005/069e5caae36a55f640093f2426a00aac to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'benchmark/ips'
def num
@num ||= 2**18
end
def foo
@foo ||= Array.new(num) { nil }.compact.any?
end
def bar
return @bar if defined? @bar
(@bar = Array.new(num) { nil }.compact.any?)
end
Benchmark.ips do |benchmark|
benchmark.config(time: 5, warmup: 5)
benchmark.report('foo') { foo }
benchmark.report('bar') { bar }
benchmark.compare!
end
# Warming up --------------------------------------
# foo 5.000 i/100ms
# bar 246.574k i/100ms
# Calculating -------------------------------------
# foo 59.063 (± 3.4%) i/s - 295.000 in 5.000007s
# bar 7.013M (± 2.9%) i/s - 35.260M in 5.032246s
# Comparison:
# bar: 7013241.0 i/s
# foo: 59.1 i/s - 118741.56x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment