如 Codeacademy 课程所示,重构是否有性能优势?

Are there performance benefits from refactoring as shown in the codeacademy course?

我目前 运行 完成了 CodeAcademy Ruby 课程,并且学习了重构部分。

例子是

if 1<2
       puts 'string'
end

puts "One is less than two!" if 1 < 2
puts 1 < 2 ? "One is less than two!" : "One is not less than two."

以及其他类似 if/elif/else 语句到 case 语句以及使用 'implicit return' 语法并将 for 循环交换到

3.times do
  puts "I'm a refactoring master!"
end

除了简单地提高可读性之外,这样做还有什么好处吗?在 Python 中有 pythonic 的做事方式,这似乎在 Ruby 中是一样的。但是,如果您使用多种语言进行编程并且不记得每种语言的约定,那么保持简单并保持原样的 for 循环似乎更有意义 - 对于其他语句也是如此,除非这实际上有性能优势.

是的,单行更像是一种 Ruby 主义的方式。没关系,您可以通过使用 benchmark 模块来了解自己的速度。

亲自查看速度差异:

require 'benchmark'

iterations = 100000000

Benchmark.bm do |bm|
  # joining an array of strings
  bm.report do
      (1..iterations).each do
          if 1<2
      true
    end
    end

  end

  # using string interpolation
  bm.report do
      (1..iterations).each do
        true if 1<2
    end
  end

   # using string interpolation
  bm.report do
      (1..iterations).each do
         1 < 2 ? true: false
    end
  end
end

结果:

       user     system      total        real
   5.850000   0.020000   5.870000 (  5.885982)
   5.780000   0.020000   5.800000 (  5.826295)
   5.600000   0.020000   5.620000 (  5.640354)