Skip to content

Instantly share code, notes, and snippets.

@SpringMT
Created October 4, 2012 08:48
Show Gist options
  • Select an option

  • Save SpringMT/3832317 to your computer and use it in GitHub Desktop.

Select an option

Save SpringMT/3832317 to your computer and use it in GitHub Desktop.
push vs <<
#!/usr/bin/env ruby
# encoding: UTF-8
require 'benchmark'
n = 1000000
array = []
Benchmark.bm(7, ">total:", ">ave:") do |x|
a = x.report("push") { n.times{ array.push 1 } }
b = x.report("<<") { n.times{ array << 1 } }
end
@nagachika
Copy link

2つの x.report の間に GC.start を入れてみるとどうでしょう。
また x.report の順番を反転してみるとどうなるでしょう?
手元では内容によらず後にしたほうが遅くなり、GC.start を挿入するとその傾向が少なくなりました。

肝は user/system は短いのに real が遅くなっている点で文字列版はヒープにメモリをたくさん取るのでその後にGCが走るタイミングがたまたま入ったところが遅くみえてしまいます。

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