Is there a performance gain in using single quotes vs double quotes in ruby?

前端 未结 14 721
挽巷
挽巷 2020-11-27 10:32

Do you know if using double quotes instead of single quotes in ruby decreases performance in any meaningful way in ruby 1.8 and 1.9.

so if I type

qu         


        
14条回答
  •  孤街浪徒
    2020-11-27 10:51

    No difference - unless you're using #{some_var} style string interpolation. But you only get the performance hit if you actually do that.

    Modified from Zetetic's example:

    require 'benchmark'
    n = 1000000
    Benchmark.bm do |x|
      x.report("assign single") { n.times do; c = 'a string'; end}
      x.report("assign double") { n.times do; c = "a string"; end}
      x.report("assign interp") { n.times do; c = "a #{n} string"; end}  
      x.report("concat single") { n.times do; 'a string ' + 'b string'; end}
      x.report("concat double") { n.times do; "a string " + "b string"; end}
      x.report("concat interp") { n.times do; "a #{n} string " + "b #{n} string"; end}
    end
    

    output

                   user       system     total    real
    assign single  0.370000   0.000000   0.370000 (  0.374599)
    assign double  0.360000   0.000000   0.360000 (  0.366636)
    assign interp  1.540000   0.010000   1.550000 (  1.577638)
    concat single  1.100000   0.010000   1.110000 (  1.119720)
    concat double  1.090000   0.000000   1.090000 (  1.116240)
    concat interp  3.460000   0.020000   3.480000 (  3.535724)
    

提交回复
热议问题