Skip to content

Instantly share code, notes, and snippets.

@chrismaximin
Created September 14, 2018 14:20
Show Gist options
  • Save chrismaximin/df4e08b4ef81e3835406923fa234f3b0 to your computer and use it in GitHub Desktop.
Save chrismaximin/df4e08b4ef81e3835406923fa234f3b0 to your computer and use it in GitHub Desktop.
Ruby next and +
require 'benchmark/ips'
ARRAY = [*1..1000]
def one_plus
ARRAY.each { |a| 1 + a }
end
def plus_one
ARRAY.each { |a| a + 1 }
end
def next_number
ARRAY.each { |a| a.next }
end
def next_direct_number
ARRAY.each { |a| 1.next }
end
def send_one_plus
ARRAY.each { |a| 1.send(:+, a) }
end
def send_plus_one
ARRAY.each { |a| a.send(:+, 1) }
end
def send_next_number
ARRAY.each { |a| a.send(:next) }
end
def send_next_direct_number
ARRAY.each { |a| 1.send(:next) }
end
Benchmark.ips do |bm|
bm.report('1 + n') { one_plus }
bm.report('n + 1') { plus_one }
bm.report('n.next') { next_number }
bm.report('1.next') { next_direct_number }
bm.report('send 1 + n') { send_one_plus }
bm.report('send n + 1') { send_plus_one }
bm.report('send n.next') { send_next_number }
bm.report('send 1.next') { send_next_direct_number }
bm.compare!
end
Warming up --------------------------------------
1 + n 2.190k i/100ms
n + 1 2.255k i/100ms
n.next 1.742k i/100ms
1.next 1.772k i/100ms
send 1 + n 1.080k i/100ms
send n + 1 1.061k i/100ms
send n.next 1.076k i/100ms
send 1.next 1.191k i/100ms
Calculating -------------------------------------
1 + n 21.053k (±13.9%) i/s - 102.930k in 5.010651s
n + 1 22.159k (± 9.5%) i/s - 110.495k in 5.042680s
n.next 17.642k (± 9.2%) i/s - 88.842k in 5.096675s
1.next 17.488k (± 9.4%) i/s - 86.828k in 5.022953s
send 1 + n 11.169k (± 7.5%) i/s - 56.160k in 5.061649s
send n + 1 11.066k (± 7.7%) i/s - 55.172k in 5.019816s
send n.next 11.745k (± 9.4%) i/s - 58.104k in 5.001579s
send 1.next 11.716k (± 9.5%) i/s - 58.359k in 5.034780s
Comparison:
n + 1: 22158.6 i/s
1 + n: 21052.9 i/s - same-ish: difference falls within error
n.next: 17642.2 i/s - 1.26x slower
1.next: 17487.9 i/s - 1.27x slower
send n.next: 11745.4 i/s - 1.89x slower
send 1.next: 11716.1 i/s - 1.89x slower
send 1 + n: 11168.9 i/s - 1.98x slower
send n + 1: 11066.3 i/s - 2.00x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment