开发者

Is there any performance difference between these two code examples?

开发者 https://www.devze.com 2023-01-06 18:32 出处:网络
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.

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 -%>


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.


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.


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


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


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 %>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号