Skip to content

Instantly share code, notes, and snippets.

@jrunning
Last active February 20, 2016 18:20
Show Gist options
  • Select an option

  • Save jrunning/83294acc5daea3b4ecbf to your computer and use it in GitHub Desktop.

Select an option

Save jrunning/83294acc5daea3b4ecbf to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
def data
Array.new(40000) do
[ rand(-100..0), rand(0..100) ]
end
end
def assign_destruct(data)
data.map {|a| a[0] = a[0].abs.to_s; a }
end
def assign_nondestruct(data)
data.map {|a| a = a.dup; a[0] = a[0].abs.to_s; a }
end
def splat(data)
data.map {|first, *rest| [ first.abs.to_s, *rest ] }
end
Benchmark.ips do |x|
x.report('assign destructive') { assign_destruct(data) }
x.report('assign nondestructive') { assign_nondestruct(data) }
x.report('splat') { splat(data) }
x.compare!
end
Calculating -------------------------------------
assign destructive 4.000 i/100ms
assign nondestructive 3.000 i/100ms
splat 3.000 i/100ms
-------------------------------------------------
assign destructive 46.936 (± 4.3%) i/s - 236.000
assign nondestructive 34.380 (± 5.8%) i/s - 174.000
splat 32.821 (± 6.1%) i/s - 165.000
Comparison:
assign destructive: 46.9 i/s
assign nondestructive: 34.4 i/s - 1.37x slower
splat: 32.8 i/s - 1.43x slower
@ndnenkov

Copy link
Copy Markdown

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment