Ruby is a fast language, and a great one in so many ways, but nothing in this world is truly free. It’s very easy to do things that seem inconsequential but that later can bring your application to a grinding halt. In this post, I’ll outline five important ways that you can avoid some of the most common problems Rails apps encounter.

Before continuing, a disclaimer: do not take these tips and refactor your code ad-hoc. Take everything with a grain of salt and perform your own measurements to determine which pieces of your app are slow. Before making any performance optimizations, get set up with a profiling tool, like RubyProf, New Relic, Scout, etc. You always want to know where the most significant bottlenecks are for you, and focus your efforts there first.

Eager Load Associations

The most common and significant problem that I’ve seen in Rails apps has been the lack of eager loaded associations. A simple extra _:include_ when performing ActiveRecord finds will prevent 1+N queries. So for example, if you are displaying a list of articles on your blog homepage and want to display the author’s name as well, load the posts with Post.all(:include => :author). For those complex pages, eager loading works multiple levels deep. Newer versions of ActiveRecord handle complex eager loading cases much more elegantly by splitting up a large join query into multiple smaller queries that make better sense.

Note: only perform the eager load when you actually plan to use the objects, because there’s fairly significant overhead to creating many ActiveRecord objects.

Do Database Work In the Database

In the same vein as the first tip, try leveraging the database when it makes sense. Relational databases are designed to query large amounts of data and return results; Ruby is not.

For example, if you want to check if the user currently logged in has commented on an article, you don’t need to load all the comments for that article. Iterate through each one, and check whether at least one comment was created by the current user. Doing this will instantiate objects for every single comment and then instantly discard them after the check is done. A much better way to obtain the same result is to push the logic to the database by doing a SELECT COUNT statement. ActiveRecord has an easy way to do this: Article.comments.count(:conditions => ["user_id = ?", current_user.id]) > 0

Do as Little as Possible During the HTTP Request Cycle

You want to be able to return a response to the end user’s request as quickly as possible, so only do the bare minimum needed to return the response and defer everything else. Actually sending out an email is relatively slow and users don’t generally care if emails are sent during the request cycle or right after.

Whether this is implemented using a simple Ruby thread or a robust, distributed queuing system like RabbitMQ doesn’t really matter. Rails 3 will ship with a default queuing system, but until then, I suggest checking out DelayedJob and BackgroundJob.

Know Your Gems and Plugins

As Rails applications get more complicated, a good thing to do is to use existing plugins and gems instead of recreating the work in house. This usually introduces a significant amount of new code to the application that is relatively unknown.

There are many great Rails plugins out there. But before depending on a new gem or plugin, I suggest at least skimming the source — check for any craziness. Also be sure you’re using plugins for their intended purposes — or things are likely to go awry.

Avoid Creating Unnecessary Objects

Every time Ruby’s garbage collector is triggered, Ruby will stop running your code and start cleaning up unused objects. This process can take between 100 and 400ms on MRI (JRuby has a better behaved, tunable garbage collector through the JVM), which is a noticeable period of time. Avoid this as much as possible. This means avoid creating unnecessary objects. I have already mentioned a couple of ways to do this in the previous tips.

In general, the best way to avoid the unnecessary creation of objects is to understand how Ruby and the libraries in use work. For example, understand the difference between these two snippets:

sentences.map { |s| s.strip }
sentences.each { |s| s.strip! }

The first snippet creates a new Array object and a new String object for each element in the Array. The second snippet just mutates the String objects in the Array without creating new Ruby objects.

Granted, this tip only makes a significant difference when dealing with large data structures, but it’s a good idea to keep in the back of your mind whether or not you actually need to duplicate objects. If you have arrays containing thousands of ActiveRecord objects and use reject vs. reject!, you’ve just created a second array which could potentially have thousands of objects.

There are many other aspects of a Ruby on Rails application that can cause bottlenecks; listing them all is obviously impossible. That said, the most important thing to learn is how to locate these bottlenecks. Solving them can be handled on a case by case basis.

转载于:https://www.cnblogs.com/only4agile/archive/2009/10/30/1593178.html

5 Ways to Speed Up Your Rails App相关推荐

  1. 第一个 Rails App 从安装到创建(windows版本)

    1. 在以下网址下载并运行 Rails 安装包: 点击打开链接 2. 检查 ruby,sqlite 和 rails 是否安装成功 2.1 查看 ruby 版本, 在命令行中输入: ruby -v 运行 ...

  2. 在你的 Rails App 中开启 ETag 加速页面载入同时节省资源

    转自http://huacnlee.com/blog/use-etag-in-your-rails-app-to-speed-up-loading/ 什么是 ETag 网上关于 ETag 的解释有很多 ...

  3. rails 3 中 app/model 目录下添加继承

    很多时候我们都需要用目录结构来让我们的源代码文件分组管理,这样方便快速找到需要的文件加以维护, rails/app/model 下大量的model文件也需要分类管理,将继承自同意model的文件放在一 ...

  4. rails 添加外键_如何在Rails后端中添加功能强大的搜索引擎

    rails 添加外键 by Domenico Angilletta 通过多梅尼科·安吉列塔(Domenico Angilletta) In my experience as a Ruby on Rai ...

  5. rails i18n模型_Rails国际化的完整指南(i18n)

    rails i18n模型 by Anastasia 由Anastasia Rails国际化的完整指南(i18n) (The Complete Guide to Rails Internationali ...

  6. vocab.com app android,Vocabulary.com

    Vocabulary.com是英语学习网站Vocabulary.com推出的app版.用户也可以看到例句都是有分类的,比如你点击商业类,软件所提供的例句便都是与商业相关的.要知道,这给写专业论文或文章 ...

  7. Rails安全导读【一】

    原文地址:[url]http://guides.rubyonrails.org/security.html[/url] --------翻译分割线 ,翻译的不好,请多多指正-------- Ruby ...

  8. vue打包的app如何设置自动清理软件缓存_使用Webpack启动你的Vue.js应用

    Webpack是开发Vue.js单页面应用(SPA)最基本的工具.通过管理负责的构建步骤能够使开发工作流非常的简单,同时也能够优化应用的大小提升应用的性能. 在这篇文章我将为大家展示Webpack是如 ...

  9. 在Heroku上部署(托管)Rails项目

    2019独角兽企业重金招聘Python工程师标准>>> ①.安装heroku: $ gem install heroku ②.先要生成一个公钥,使用命令: $ ssh-keygen ...

最新文章

  1. Juniper的路由器、防火墙、交换机如何恢复出厂配置
  2. linux下mysql主从复制搭建
  3. 关于poll机制应用及驱动
  4. 常用的rpm和yum的一些命令
  5. Android Studio发布项目到jcenter
  6. Linux CentOS6离线安装Jupyter notebook
  7. 2017.9.15 最大数maxnumber 思考记录
  8. iphone分屏功能怎么用_你用iPhone手机,没学会这7个功能,难怪会说手机不好用...
  9. 数字图像处理怎么讲yiq空间变成rgb空间_【JTRP】屏幕空间深度边缘光 Screen Space Depth Rimlight...
  10. 什么是SQL脚本?及作用和命令
  11. C# sqlhelper
  12. 手机连接Fiddler后无法上网问题解决
  13. 判断时间是否在本月之内
  14. 手机刷机后丢失照片恢复怎么做到?
  15. 极客时间和极客学院_极客需要告诉我们的父母有关安全可靠地在线购物的信息
  16. 使用O2OA二次开发搭建企业办公平台(十三)流程开发篇:报销审批流程表单开发...
  17. Sigma Designs SMP8910媒体处理器的3DTV、蓝光和OTT体验
  18. python cmap,使用Matplotlib绘图时获取意想不到的输出 - Cmap - Python
  19. numpy pandas series 数据维度的变换
  20. DRG/DIP 分组器接口开放调用

热门文章

  1. 百度DuerOS与高通合推手机语音交互解决方案,谁会欢喜谁要愁?
  2. 人类与AI结合的最佳形态是什么样?
  3. 如何打开Assets.car文件
  4. mysql使用substring_index达到splite功能
  5. 大规模Schedule任务实现方案
  6. Lua-pb 升级到Lua5.3
  7. 关于Floyd-Warshall算法由前趋矩阵计算出的最短路径反映出了算法的执行过程特性的证明...
  8. 说人话很难。。。。。。
  9. IE6下top.location.href失效的问题
  10. Redis 常用命令(学习笔记二)