String concatenation in Ruby

前端 未结 16 1183
青春惊慌失措
青春惊慌失措 2020-11-28 01:28

I am looking for a more elegant way of concatenating strings in Ruby.

I have the following line:

source = \"#{ROOT_DIR}/\" << project <<          


        
16条回答
  •  甜味超标
    2020-11-28 01:42

    Here's another benchmark inspired by this gist. It compares concatenation (+), appending (<<) and interpolation (#{}) for dynamic and predefined strings.

    require 'benchmark'
    
    # we will need the CAPTION and FORMAT constants:
    include Benchmark
    
    count = 100_000
    
    
    puts "Dynamic strings"
    
    Benchmark.benchmark(CAPTION, 7, FORMAT) do |bm|
      bm.report("concat") { count.times { 11.to_s +  '/' +  12.to_s } }
      bm.report("append") { count.times { 11.to_s << '/' << 12.to_s } }
      bm.report("interp") { count.times { "#{11}/#{12}" } }
    end
    
    
    puts "\nPredefined strings"
    
    s11 = "11"
    s12 = "12"
    Benchmark.benchmark(CAPTION, 7, FORMAT) do |bm|
      bm.report("concat") { count.times { s11 +  '/' +  s12 } }
      bm.report("append") { count.times { s11 << '/' << s12 } }
      bm.report("interp") { count.times { "#{s11}/#{s12}"   } }
    end
    

    output:

    Dynamic strings
                  user     system      total        real
    concat    0.050000   0.000000   0.050000 (  0.047770)
    append    0.040000   0.000000   0.040000 (  0.042724)
    interp    0.050000   0.000000   0.050000 (  0.051736)
    
    Predefined strings
                  user     system      total        real
    concat    0.030000   0.000000   0.030000 (  0.024888)
    append    0.020000   0.000000   0.020000 (  0.023373)
    interp    3.160000   0.160000   3.320000 (  3.311253)
    

    Conclusion: interpolation in MRI is heavy.

提交回复
热议问题