在 ruby​​ 中使用单引号与双引号是否有性能提升? [英] Is there a performance gain in using single quotes vs double quotes in ruby?

查看:44
本文介绍了在 ruby​​ 中使用单引号与双引号是否有性能提升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否知道在 ruby​​ 中使用双引号代替单引号是否会以任何有意义的方式降低 ruby​​ 1.8 和 1.9 中的性能.

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.

所以如果我输入

question = 'my question'

是否比

question = "my question"

我想 ruby​​ 会在遇到双引号时尝试确定是否需要评估某些内容,并且可能会花费一些周期来这样做.

I imagine that ruby tries to figure out if something needs to be evaluated when it encounters double quotes and probably spends some cycles doing just that.

推荐答案

$ 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)

注意:我已经更新了它以使其适用于较新的 Ruby 版本,并清理了标头,并在更快的系统上运行基准测试.

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.

这篇关于在 ruby​​ 中使用单引号与双引号是否有性能提升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆