简体   繁体   English

Ruby:%w性能

[英]Ruby : %w performance

perhaps a simple question, but we are discussing about whether it better to use this snipper: 也许是一个简单的问题,但我们正在讨论是否更好地使用这个片段:

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

versus

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

We just want to understand which is the most performant way, ignoring the sytax suggering from Ruby. 我们只想了解哪种方法性能最佳,忽略了Ruby的sytax构造。 From what I could on the web, the %w literal seems to be a shorthand to string.split on the provided whitespace string. 从我在网络上可以看到,%w文字似乎是提供的空白字符串上的string.split的简写。

But which one is actually the fastest? 但哪一个实际上最快?

ps : A source for the answer would be appreciated. ps:答案的来源将不胜感激。

Here's what %w and %W do, taken directly from parse.y (with ommissions): 这是%w%W直接来自parse.y (带有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;

Considering it's implemented on the parser level, I wouldn't worry too much about the performance. 考虑到它是在解析器级别实现的,我不会太担心性能。

I've done some test on my c2d: 我对我的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM