Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@phiggins

This comment has been minimized.

Copy link
Owner Author

phiggins commented Oct 22, 2014

pete@balloon:~/projects$ ruby -v benchmark_append.rb 
ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-linux]
Calculating -------------------------------------
                push     85651 i/100ms
              shovel     90835 i/100ms
              concat     80403 i/100ms
                   +    121933 i/100ms
             unshift     82516 i/100ms
           insert -1     79081 i/100ms
            insert 0     77149 i/100ms
                 []=     75169 i/100ms
                   |     32619 i/100ms
                 nil    171901 i/100ms
-------------------------------------------------
                push  1805366.8 (±0.7%) i/s -    9079006 in   5.029121s
              shovel  1878389.4 (±1.6%) i/s -    9446840 in   5.030615s
              concat  1579816.1 (±1.8%) i/s -    7959897 in   5.040190s
                   +  3635933.0 (±1.3%) i/s -   18289950 in   5.031245s
             unshift  1788963.8 (±1.3%) i/s -    8994244 in   5.028498s
           insert -1  1638090.0 (±1.4%) i/s -    8224424 in   5.021721s
            insert 0  1642330.2 (±1.2%) i/s -    8254943 in   5.027106s
                 []=  1519751.9 (±1.9%) i/s -    7667238 in   5.046921s
                   |   416418.6 (±1.3%) i/s -    2087616 in   5.014100s
                 nil 10686329.6 (±1.3%) i/s -   53461211 in   5.003663s
@zenspider

This comment has been minimized.

Copy link

zenspider commented Oct 22, 2014

Add x.compare!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.