Skip to content

Instantly share code, notes, and snippets.

@phiggins
Created October 22, 2014 03:20
Show Gist options
  • Save phiggins/a1a4c747ed4133e12210 to your computer and use it in GitHub Desktop.
Save phiggins/a1a4c747ed4133e12210 to your computer and use it in GitHub Desktop.
What is the fastest way to add one thing to an array without mutating the array?
require 'benchmark/ips'
a = (0..10).to_a
Benchmark.ips do |x|
x.report("push") { a.dup.push(100) }
x.report("shovel") { a.dup << 100 }
x.report("concat") { a.dup.concat([100]) }
x.report("+") { a + [100] }
x.report("unshift") { a.dup.unshift(100) }
x.report("insert -1") { a.dup.insert(-1, 100) }
x.report("insert 0") { a.dup.insert(0, 100) }
x.report("[]=") { b = a.dup ; b[0,0] = 100 }
x.report("|") { a | [100] }
x.report("nil") { nil }
end
@zenspider
Copy link

Add x.compare!

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