Ruby Array concat versus + speed?

后端 未结 4 600
萌比男神i
萌比男神i 2021-02-12 06:00

I did small performance test of Ruby\'s array concat() vs + operation and concat() was way too fast.

I however am not clear on why

4条回答
  •  迷失自我
    2021-02-12 06:36

    The OP's question, as noted in other answers, is comparing two operators that perform different purposes. One, concat, which is destructive to (mutates) the original array, and + which is non-destructive (pure functional, no mutation).

    I came here looking for a more comparable test, not realizing at the time, that concat was destructive. In case it's useful to others looking to compare two purely functional, non-destructive operations, here is a benchmark of array addition (array1 + array2) vs array expansion ([*array1, *array2]). Both, as far as I'm aware, result in 3 arrays being created: 2 input arrays, 1 new resulting array.

    Hint: + wins.

    Code

    # a1 is a function producing a random array to avoid caching
    a1 = ->(){ [rand(10)] }
    a2 = [1,2,3]
    n = 10_000_000
    Benchmark.bm do |b|
      b.report('expand'){ n.times{ [*a1[], *a2] } }
      b.report('add'){ n.times{ a1[]+a2 } }
    end
    

    Result

    user     system      total        real
    expand  9.970000   0.170000  10.140000 ( 10.151718)
    add  7.760000   0.020000   7.780000 (  7.792146)
    

提交回复
热议问题