Tattat
Tattat

Reputation: 15778

Is there any performance difference between these two code examples?

The code below seems to do the same thing, but does one have better performance than the other, or they are the same? Thank you.

Code 1:

<% @posts.each do |post| -%>  
post.doSomething
<% end -%>

Code 2:

<% for post in @posts %>
post.doSomething
<% end -%>

Upvotes: 1

Views: 170

Answers (6)

MKumar
MKumar

Reputation: 1524

I don't think that there is any performance difference in both of them.

@posts.each gives error when @posts array is null or blank while for ... in doesn't give error.

So if you are using each you should code like

<% unless @posts.blank? %>
   <% @posts.each do |post| -%>  
      post.doSomething
   <% end -%>
<% end %>

Upvotes: 0

Omar Qureshi
Omar Qureshi

Reputation: 9093

Performance wise - the difference should be negligible, nothing to be worried about ... however, there is a difference into what each of them does wrt variable scope, see https://gist.github.com/b07f6a11500693a2e181

Upvotes: 0

nhm tanveer
nhm tanveer

Reputation: 682

You can use "break" inside for .. in .. end :)

Upvotes: -2

Chubas
Chubas

Reputation: 18043

The widely adopted way is to use each. Not only because is more Ruby-ish, but because from Ruby 1.8.7+ each returns an Enumerator object, which can be used to do magic cool functional stuff.

Also: when in doubt, benchmark**

require "benchmark"

array = [*1..100_000]

Benchmark.bm(11) do |x|
  x.report("for .. in") { array.each{ |i| i.succ } }
  x.report("each")      { for i in array; i.succ; end }
end

** If you find the 0.00000001 nanoseconds of performance gain in your code to be relevant, probably you shouldn't be using Ruby anyway.

Upvotes: 5

Matt Briggs
Matt Briggs

Reputation: 42168

In the first one, you are passing in code you want to execute against each element in the array. In the second, you are looping over the code and doing stuff. Functionally, there is no difference. Idiomatically, rubyists will choose functional programming style APIs every time. It is a culture thing.

When it comes to perf, you shouldn't be sweating micro-optimization anyways unless its a problem. Anything that is measured in milliseconds shouldn't be considered as an issue until you actually run a profiler and find out where your code is actually slow. Most code doesn't need to run at peak efficiency, developer productivity and maintainability are way more important.

Upvotes: 4

Matchu
Matchu

Reputation: 85794

They are pretty darn equivalent, and the effect on performance is negligible. Just for the style you prefer, and be consistent.

Upvotes: 0

Related Questions