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
@SpringMT
Copy link
Author

SpringMT commented Oct 4, 2012

$ ruby array_push_vs_arrows.rb
user system total real
push 0.140000 0.000000 0.140000 ( 0.142282)
<< 0.090000 0.000000 0.090000 ( 0.100491)

@gx-hackers
Copy link

#!/usr/bin/env ruby
# encoding: UTF-8

# string.rb

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

追加するのを文字列にしたら、

#元の(SpringMTさん製)コード
$ ruby integer.rb
              user     system      total        real
push      0.080000   0.000000   0.080000 (  0.091066)
<<        0.060000   0.010000   0.070000 (  0.073333)

#文字列にしてみた場合
$ ruby string.rb
              user     system      total        real
push      0.150000   0.020000   0.170000 (  0.190723)
<<        0.120000   0.020000   0.140000 (  0.214876)

みたいに、何回やっても << の方が遅いんで、
Integertの場合は << でやって、
Stringの場合は push のほうが速いっのではと思いました!

@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