String concatenation vs. interpolation in Ruby

前端 未结 5 1141
北海茫月
北海茫月 2020-11-27 16:06

I am just starting to learn Ruby (first time programming), and have a basic syntactical question with regards to variables, and various ways of writing code.

Chris

5条回答
  •  一向
    一向 (楼主)
    2020-11-27 16:29

    If you are using a string as a buffer, I found that using concatenation (String#concat) to be faster.

    require 'benchmark/ips'
    
    puts "Ruby #{RUBY_VERSION} at #{Time.now}"
    puts
    
    firstname = 'soundarapandian'
    middlename = 'rathinasamy'
    lastname = 'arumugam'
    
    Benchmark.ips do |x|
        x.report("String\#<<") do |i|
            buffer = String.new
    
            while (i -= 1) > 0
                buffer << 'Mr. ' << firstname << middlename << lastname << ' aka soundar'
            end
        end
    
        x.report("String interpolate") do |i|
            buffer = String.new
    
            while (i -= 1) > 0
                buffer << "Mr. #{firstname} #{middlename} #{lastname} aka soundar"
            end
        end
    
        x.compare!
    end
    

    Results:

    Ruby 2.3.1 at 2016-11-15 15:03:57 +1300
    
    Warming up --------------------------------------
               String#<<   230.615k i/100ms
      String interpolate   234.274k i/100ms
    Calculating -------------------------------------
               String#<<      2.345M (± 7.2%) i/s -     11.761M in   5.041164s
      String interpolate      1.242M (± 5.4%) i/s -      6.325M in   5.108324s
    
    Comparison:
               String#<<:  2344530.4 i/s
      String interpolate:  1241784.9 i/s - 1.89x  slower
    

    At a guess, I'd say that interpolation generates a temporary string which is why it's slower.

提交回复
热议问题