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

前端 未结 14 670
挽巷
挽巷 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

    I too thought that single quoted strings might be quicker to parse for Ruby. It doesn't seem to be the case.

    Anyway, I think the above benchmark are measuring the wrong thing, though. It stands to reason that either versions will be parsed into the same internal string representations so to get the answer as to which is quicker to parse, we shouldn't be measuring performance with string variables, but rather Ruby's speed of parsing strings.

    generate.rb: 
    10000.times do
      ('a'..'z').to_a.each {|v| print "#{v}='This is a test string.'\n" }
    end
    
    #Generate sample ruby code with lots of strings to parse
    $ ruby generate.rb > single_q.rb
    #Get the double quote version
    $ tr \' \" < single_q.rb > double_q.rb
    
    #Compare execution times
    $ time ruby single_q.rb 
    
    real    0m0.978s
    user    0m0.920s
    sys     0m0.048s
    $ time ruby double_q.rb 
    
    real    0m0.994s
    user    0m0.940s
    sys     0m0.044s
    

    Repeated runs don't seem to make much difference. It still takes pretty much the same time to parse either version of the string.

提交回复
热议问题