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 |
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
追加するのを文字列にしたら、
みたいに、何回やっても << の方が遅いんで、
Integertの場合は << でやって、
Stringの場合は push のほうが速いっのではと思いました!