Ruby:%w性能

时间:2012-06-25 09:37:25

标签: ruby arrays performance

也许是一个简单的问题,但我们正在讨论是否更好地使用这个片段:

if %w(production staging).include?(Rails.env)

if ["production","staging"].include?(Rails.env)

我们只想了解哪种方法性能最佳,忽略了Ruby的sytax。从我在网络上可以看到,%w文字似乎是提供的空白字符串上string.split的简写。

但哪一个实际上最快?

p.s:感谢答案的来源。

2 个答案:

答案 0 :(得分:7)

以下是%w%W直接从parse.y获取的内容(包含提示):

case '%':
[snip]
  switch (c) {
    [snip]
    case 'W':
      lex_strterm = NEW_STRTERM(str_dword, term, paren);
      do {c = nextc();} while (ISSPACE(c));
      pushback(c);
      return tWORDS_BEG;

    case 'w':
      lex_strterm = NEW_STRTERM(str_sword, term, paren);
      do {c = nextc();} while (ISSPACE(c));
      pushback(c);
      return tQWORDS_BEG;

考虑到它是在解析器级别实现的,我不会过分担心性能。

答案 1 :(得分:3)

我在c2d上做了一些测试:

ruby -e "10000000.times { ['one', 'two'].include?('two')}"  
8.04s user 0.05s system 90% cpu 8.912 total

ruby -e "10000000.times { %w(one two).include?('two')}"  
8.03s user 0.05s system 93% cpu 8.608 total
相关问题