Ruby - Array.join versus String Concatenation (Efficiency)

后端 未结 5 1798
面向向阳花
面向向阳花 2021-02-05 06:56

I recall getting a scolding for concatenating Strings in Python once upon a time. I was told that it is more efficient to create an List of Strings in Python and join them later

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 07:20

    Try it yourself with the Benchmark class.

    require "benchmark"
    
    n = 1000000
    Benchmark.bmbm do |x|
      x.report("concatenation") do
        foo = ""
        n.times do
          foo << "foobar"
        end
      end
    
      x.report("using lists") do
        foo = []
        n.times do
          foo << "foobar"
        end
        string = foo.join
      end
    end
    

    This produces the following output:

    Rehearsal -------------------------------------------------
    concatenation   0.300000   0.010000   0.310000 (  0.317457)
    using lists     0.380000   0.050000   0.430000 (  0.442691)
    ---------------------------------------- total: 0.740000sec
    
                        user     system      total        real
    concatenation   0.260000   0.010000   0.270000 (  0.309520)
    using lists     0.310000   0.020000   0.330000 (  0.363102)
    

    So it looks like concatenation is a little faster in this case. Benchmark on your system for your use-case.

提交回复
热议问题