Ruby - Array.join versus String Concatenation (Efficiency)

后端 未结 5 1794
面向向阳花
面向向阳花 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:17

    Funny, benchmarking gives surprising results (unless I'm doing something wrong):

    require 'benchmark'
    
    N = 1_000_000
    Benchmark.bm(20) do |rep|
    
      rep.report('+') do
        N.times do
          res = 'foo' + 'bar' + 'baz'
        end
      end
    
      rep.report('join') do
        N.times do
          res = ['foo', 'bar', 'baz'].join
        end
      end
    
      rep.report('<<') do
        N.times do
          res = 'foo' << 'bar' << 'baz'
        end
      end
    end
    

    gives

    jablan@poneti:~/dev/rb$ ruby concat.rb 
                              user     system      total        real
    +                     1.760000   0.000000   1.760000 (  1.791334)
    join                  2.410000   0.000000   2.410000 (  2.412974)
    <<                    1.380000   0.000000   1.380000 (  1.376663)
    

    join turns out to be the slowest. It might have to do with creating the array, but that's what you would have to do anyway.

    Oh BTW,

    jablan@poneti:~/dev/rb$ ruby -v
    ruby 1.9.1p378 (2010-01-10 revision 26273) [i486-linux]
    

提交回复
热议问题