Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?

后端 未结 7 1000
一生所求
一生所求 2020-11-28 18:17

I am working through Ruby Koans.

The test_the_shovel_operator_modifies_the_original_string Koan in about_strings.rb includes the follo

7条回答
  •  没有蜡笔的小新
    2020-11-28 19:02

    Performance proof:

    #!/usr/bin/env ruby
    
    require 'benchmark'
    
    Benchmark.bmbm do |x|
      x.report('+= :') do
        s = ""
        10000.times { s += "something " }
      end
      x.report('<< :') do
        s = ""
        10000.times { s << "something " }
      end
    end
    
    # Rehearsal ----------------------------------------
    # += :   0.450000   0.010000   0.460000 (  0.465936)
    # << :   0.010000   0.000000   0.010000 (  0.009451)
    # ------------------------------- total: 0.470000sec
    # 
    #            user     system      total        real
    # += :   0.270000   0.010000   0.280000 (  0.277945)
    # << :   0.000000   0.000000   0.000000 (  0.003043)
    

提交回复
热议问题