0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Ruby] 配列の結合について

Posted at

Rubyによる配列の結合処理について調べていみました。
間違っていればご指摘お願いします!

計測コード

require 'benchmark'

n = 10000
y = 10
hoge_array = Array.new(y, "hoge")

Benchmark.bm(10) do |r|
  r.report "flatten" do
    n.times{ [hoge_array, hoge_array, "hoge"].flatten }
  end

  r.report "splat" do
    n.times{ [*hoge_array, *hoge_array, "hoge"] }
  end

  r.report "+" do
    n.times{ hoge_array + hoge_array + ["hoge"] }
  end
end

ベンチマーク

n = 10
y = 10
user     system      total        real
flatten      0.000055   0.000004   0.000059 (  0.000053)
splat        0.000027   0.000001   0.000028 (  0.000028)
+            0.000012   0.000001   0.000013 (  0.000012)

n = 1000
y = 1000
user     system      total        real
flatten      0.104978   0.005486   0.110464 (  0.112003)
splat        0.010389   0.009051   0.019440 (  0.019443)
+            0.008141   0.010716   0.018857 (  0.018884)


n = 10
y = 10000
user     system      total        real
flatten      0.009268   0.000414   0.009682 (  0.009682)
splat        0.001068   0.000962   0.002030 (  0.002049)
+            0.000805   0.000758   0.001563 (  0.001563)

n = 10000
y = 10
user     system      total        real
flatten      0.027865   0.001622   0.029487 (  0.029749)
splat        0.012830   0.000590   0.013420 (  0.013561)
+            0.005672   0.000507   0.006179 (  0.006228)

まとめ

flatten < splat < + の順に速度が速いことが分かりました!!
シンプルな結合の際は、迷わず+の実装を選択していきたいと思いました。splat展開は、色々な場面で汎用的に使用できるのでありがたいです。flattenは、想像以上にパフォーマンスが悪かったので必要な場面のみ使用していきたと思います!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?