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

I'm currently running through the CodeAcademy Ruby course and have hit a refactoring section.

Examples are

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."

And others like if/elif/else statements to case statements as well as using the 'implicit return' syntax and swapping a for loop to

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

Are there any benefits to this other than simply making it more readable? In Python there are pythonic ways of doing things and it seems this is the same in Ruby. However if you do program in multiple language and can't remember the conventions for each it seems to make more sense to just keep it simple and leave a for loop as it is - likewise for other statements unless there is actually a performance benefit to this.

Answers


Yes, the one liner is more of a Ruby-ist way. Nevermind, you can see about the speed for yourself with the use of benchmark module.

See the sped diff for yourself:

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

Results:

       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)

Need Your Help

variables in batch scripts

php deployment syntax batch-file scripting

I'm trying to set up a batch file to automatically deploy a php app to a web server. Basically, what I want is an entirely automated process: I would just give it a revision number from the repos...

Why does DefaultHttpClient send data over a half-closed socket?

java android tcp apache-httpclient-4.x

I'm using DefaultHttpClient with a ThreadSafeClientConnManager on Android (2.3.x) to send HTTP requests to a my REST server (embedded Jetty).