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

前端 未结 14 722
挽巷
挽巷 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:58

    No one happened to measure concatenation vs interpolation though:

    $ ruby -v
    ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin9.6.2]
    $ cat benchmark_quotes.rb
    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 string #{'b 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}
    end
    
    $ ruby -w benchmark_quotes.rb 
          user     system      total        real
    assign single  2.600000   1.060000   3.660000 (  3.720909)
    assign double  2.590000   1.050000   3.640000 (  3.675082)
    assign interp  2.620000   1.050000   3.670000 (  3.704218)
    concat single  3.760000   1.080000   4.840000 (  4.888394)
    concat double  3.700000   1.070000   4.770000 (  4.818794)
    

    Specifically, note assign interp = 2.62 vs concat single = 3.76. As icing on the cake, I also find interpolation to be more readable than 'a' + var + 'b' especially with regard to spaces.

提交回复
热议问题