Created
October 4, 2012 08:48
-
-
Save SpringMT/3832317 to your computer and use it in GitHub Desktop.
push vs <<
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 |
Author
#!/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 のほうが速いっのではと思いました!
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
$ 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)