require 'benchmark'
huge_ary_1 = Array.new(1_000_000) { rand(5_000_000..30_000_00) }
huge_ary_2 = Array.new(1_000_000) { rand(35_000_000..55_000_00) }
Benchmark.bm do |bm|
p '-------------------CONCAT ----------------'
bm.report { huge_ary_1.concat(huge_ary_2) }
p '------------------- PUSH ----------------'
bm.report { huge_ary_1.push(*huge_ary_2) }
end
结果:
user system total real
"-------------------CONCAT ----------------"
0.000000 0.000000 0.000000 ( 0.009388)
"------------------- PUSH ----------------"
example/array_concat_vs_push.rb:13:in `block (2 levels) in <main>': stack level too deep (SystemStackError)
正如您所看到的,当数组足够大时,使用push会抛出错误: stack level too deep (SystemStackError)。