Speech of Nihad Abbasov, Senior Software Engineer at Digital Classifieds, at Ruby Meditation 27, Dnipro, 19.05.2019
Slideshare -
Next conference - http://www.rubymeditation.com/
How fast is your code? Performance is crucial as your startup grows, and optimizing your application can make a huge impact on user experience. During this talk, you will learn hints, techniques and best practices for improving the overall speed of your Ruby application.
Announcements and conference materials https://www.fb.me/RubyMeditation
News https://twitter.com/RubyMeditation
Photos https://www.instagram.com/RubyMeditation
The stream of Ruby conferences (not just ours) https://t.me/RubyMeditation
16. Use #detect instead of
#select + first
# slow
[*1..100].select { |e| e
== 20 }.first
# fast
[*1..100].detect { |e| e
== 20 }
17. Use #reverse.detect
instead of #select.last
# slow
[*1..100].select { |e|
(e % 10).zero? }.last
# fast
[*1..100].reverse.detect
{ |e| (e % 10).zero? }
18. Use #each_key instead of
#keys + each
# slow
HASH.keys.each { |k| k }
# fast
HASH.each_key { |k| k }
HASH = Hash[*('aa'..'zz')]
19. Use #key? instead of
#keys + include?
# slow
HASH.keys.include? 'zz'
# fast
HASH.key? 'zz'
HASH = Hash[*('aa'..'zz')]
20. Use #value? instead of
#values + include?
# slow
HASH.values.include? 'zz'
# fast
HASH.value? 'zz'
HASH = Hash[*('aa'..'zz')]
33. Use select to get only
the necessary data
@users = User.select(:name, :email).limit(20)
<% @users.each do |user| %>
<%= user.name %><br>
<%= user.email %>
<% end %>
34. Use size on relation
instead of count
@messages = current_user.messages.unread
<% @messages.each do |message| %>
<%= message.body %>
<% end %>
<h2>Unread Messages: <%= @messages.size %></h2>
36. Indexes for
polymorphic associations
class Comment
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class Post
has_many :comments, as: :commentable
has_one :user
end
39. Use subqueries
with ActiveRecord
# 2 separate queries
Ad.where(id: current_user.bookmarks.pluck(:ad_id))
# 1 query with subquery
Ad.where(id: current_user.bookmarks.select(:ad_id))
61. Use WEBP
for images
Supported by:
▪ Google Chrome (desktop) 17+
▪ Google Chrome for Android version 25+
▪ Microsoft Edge 18+
▪ Firefox 65+
▪ Opera 11.10+
▪ Native web browser, Android 4.0+ (ICS)