【问题标题】:Ruby : %w performanceRuby : %w 性能
【发布时间】:2012-06-26 13:24:33
【问题描述】:

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

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

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

我们只是想了解哪种方式最高效,忽略 Ruby 的语法。根据我在网络上的信息, %w 文字似乎是提供的空白字符串上 string.split 的简写。

但实际上哪一个是最快的?

p.s : 答案来源将不胜感激。

【问题讨论】:

  • 您在其他地方遇到了更糟糕的性能问题。比如,我不知道,数据库?花时间修复这些更有意义。
  • Shees。 Stackoverflow 是用来发布问题的,不是吗?我们想知道这个问题。我们的数据库是完全集群的,等等,有集群的网络服务器等等。我们正在满足我们的要求和一切,我们只是好奇这个花絮,这有多难
  • @LarsHaugseth, @NekoNova:顺便说一下,Rails.env 不是简单的字符串。您可以使用if Rails.env.production? || Rails.env.staging? 并避免使用临时数组。
  • @SergioTulentsev 虽然这个实现依赖于method_missing,但这也很昂贵,只是方式不同。
  • Sergio,如果我们现在收到关于 ActiveSupport::StringInquirer 性能的问题,那是你的错 :)

标签: ruby arrays performance


【解决方案1】:

这是%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;

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

【讨论】:

    【解决方案2】:

    我在我的 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
    

    【讨论】:

    • 1.9.3-p125 :002 > 要求'基准' => true 1.9.3-p125 :003 > puts Benchmark.measure{ 1000000.times 做 ["production","staging"]。 include?("staging") end} 0.970000 0.000000 0.970000 (0.976099) => nil 1.9.3-p125 :004 > puts Benchmark.measure {1000000.times do %w(production staging).include?("staging") end 0.970000 0.000000 0.970000 (0.973253) => nil 是我的结果。似乎 %w 更快:S
    • 首先,您应该在此处放弃对include? 的调用,因为在两个字符串的数组上调用这两种情况所需的时间完全相同。其次,当我多次运行这两种情况时,两个案例之间的差异小于同一案例不同运行之间的差异。
    • 在没有包含的情况下重新运行测试。确实得到您描述的结果。
    猜你喜欢
    • 2010-10-16
    • 2018-10-18
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2013-07-30
    相关资源
    最近更新 更多