My app is reaching a point where I must begin optimizing for performance. I’ve posted some code from my view that I feel can be improved.
In the view, I am treating the first item in the index a certain way and the rest of the items another way. Each time a new item is iterated over, it is being checked (Ruby asks itself.. does this item have an index of 0?)
I feel like performance can be improved if I can stop that behavior by treating the first item special with index.first? and treating the other items another way (without even checking whether they have an index of zero) How can this be done?
<% @links.each_with_index do |link, index| %>
<% if link.points == 0 then @points = "?" else @points = link.points %>
<% end %>
<% if index == 0 then %>
<h1> First Item </h1>
<% else %>
<h1> Everything else </h1>
<% end %>
<% end %>
<% end %>
You can do this non-destructively like so:
…where
firstwill be the first element (ornilif my_array was empty) andrestwill always be an array (possibly empty).You can get the same results more easily if it’s OK to modify your array:
However, this will only clean up your code; it will make no measurable performance difference.