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

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

    $ ruby -v
    ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.0.0]
    
    $ cat benchmark_quotes.rb
    # As of Ruby 1.9 Benchmark must be required
    require 'benchmark'
    
    n = 1000000
    Benchmark.bm(15) 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("concat single") { n.times do; 'a string ' + 'b string'; end}
      x.report("concat double") { n.times do; "a string " + "b string"; end}
    end
    
    $ ruby benchmark_quotes.rb 
    
                          user     system      total        real
    assign single     0.110000   0.000000   0.110000 (  0.116867)
    assign double     0.120000   0.000000   0.120000 (  0.116761)
    concat single     0.280000   0.000000   0.280000 (  0.276964)
    concat double     0.270000   0.000000   0.270000 (  0.278146)
    

    Note: I've updated this to make it work with newer Ruby versions, and cleaned up the header, and run the benchmark on a faster system.

    This answer omits some key points. See especially these other answers concerning interpolation and the reason there is no significant difference in performance when using single vs. double quotes.

提交回复
热议问题