How to Improve Ruby On Rails performance (1)

Source: Internet
Author: User
Tags ruby on rails

How to Improve Ruby On Rails performance (1)

1 Introduction to Introduction

It is always said that Rails is so slow that it has become a common issue in the Ruby and Rails communities. However, this statement is not true. As long as you use Rails correctly, it is not difficult to increase the running speed of your application by 10 times. So how can we optimize your application? Let's take a look at the following content.

1.1 how to optimize a Rails app

This slows down your Rails application for the following two reasons:

Rails is a pleasant framework, and Ruby is also a concise and elegant language. However, if it is abused, performance will be greatly affected. There are a lot of jobs that are not suitable for Ruby and Rails. You 'd better use other tools. For example, the database has obvious advantages in big data processing, and the R language is especially suitable for statistics-related work.

Memory problems are the primary cause of Slow Ruby applications. The 80-20 rule for Rails performance optimization is like this: the 80% increase is due to the memory optimization, and the remaining 20% is another factor. Why is memory consumption so important? Because the more memory you allocate, the more work you need to do in Ruby mongouby's garbage collection mechanism. Rails occupies a large amount of memory, and each application occupies nearly 100 MB of memory after it is started on average. If you do not pay attention to memory control, it is very likely that your program memory will grow by more than 1 GB. So much memory needs to be recycled, it's no wonder that most of the execution time is occupied by GC.

2. How can we make a Rails application run faster?

There are three ways to make your application faster: resizing, caching, and code optimization.

Resizing is now easy to implement. Heroku basically does this for you, while Hirefire makes this process more automated. You can find more information about automatic resizing. Other hosting environments provide similar solutions. In short, you can use it. However, please note that resizing is not a silver bullet that improves performance. If your application only needs to respond to a request within five minutes, resizing is useless. In addition, using Heroku + Hirefire can easily lead to overdraft of your bank account. I have seen Hirefire scale up an application to 36 entities, and I paid $3100 for it. I immediately removed two instances and optimized the code.

Rails cache is also easy to implement. The block cache in Rails 4 is very good. Rails documents are excellent materials on Cache knowledge. There is also a Cheyne Wallace article about Rails performance that is worth reading. Now it is easy to set Memcached. However, compared with resizing, caching cannot be the ultimate solution to performance problems. If your code cannot run properly, you will find that you will spend more and more resources on the cache until the cache can no longer speed up.

The only reliable way to make your Rails application faster is code optimization. In Rails, this is memory optimization. Naturally, if you accept my advice and avoid using Rails outside of its design capabilities, you will have less code to optimize.

2.1 avoid memory-intensive Rails features

Some features of Rails consume a lot of memory, resulting in additional garbage collection. The list is as follows.

2.1.1 serialization Program

A serialization program is a practical method for reading strings from a database as Ruby data types.

 
 
  1. class Smth < ActiveRecord::Base 
  2.   serialize :data, JSON 
  3. end 
  4. Smth.find(...).data 
  5. Smth.find(...).data = { ... } 
  6. But convenience comes with 3x memory overhead. If you store 100M in data column, expect to allocate 300M just to read it from the database. 

It consumes more memory for effective serialization. You can see it by yourself:

 
 
  1. class Smth < ActiveRecord::Base 
  2.   def data 
  3.     JSON.parse(read_attribute(:data)) 
  4.   end 
  5.   def data=(value) 
  6.     write_attribute(:data, value.to_json) 
  7.   end 
  8. end 

This only requires two times of memory overhead. Some people, including myself, see the Rails JSON serialization program memory leakage, about 10% of the data volume per request. I don't understand why. I do not know whether there is a replicable situation. If you have experience or know how to reduce the memory, please let me know.

2.1.2 activity records

It is easy to manipulate data with ActiveRecord. However, ActiveRecord essentially encapsulates your data. If you have 1 GB of table data, ActiveRecord indicates that it will take 2 GB, in some cases more. Yes. In 90% of the cases, you get extra convenience. But sometimes you don't need it. For example, batch update can reduce the overhead of ActiveRecord. The following code does not instantiate any model or run verification and callback.

Book. where ('title LIKE? ',' % Rails % '). update_all (author: 'David ')

In the following scenario, it only executes SQL update statements.

 
 
  1. update books 
  2.   set author = 'David' 
  3.   where title LIKE '%Rails%' 
  4. Another example is iteration over a large dataset. Sometimes you need only the data. No typecasting, no updates. This snippet just runs the query and avoids ActiveRecord altogether: 
  5. result = ActiveRecord::Base.execute 'select * from books' 
  6. result.each do |row| 
  7.   # do something with row.values_at('col1', 'col2') 
  8. end 

2.1.3 string callback

The Rails callback is like saving before/after, the action before/after, and a lot of use. However, this method you write may affect your performance. There are three methods you can write, such as: callback before saving:

 
 
  1. before_save :update_status 
  2. before_save do |model| 
  3. model.update_status 
  4. end 
  5. before_save “self.update_status” 

The first two methods can run well, but the third method cannot. Why? Because the execution of the Rails callback needs to store the execution context variables, constants, global instances, and so on) is in the callback. If your application is large, you will eventually replicate a large amount of data in the memory. The callback can be executed at any time and cannot be recycled until your program ends.

It is symbolic that callback saves 0.6 seconds for each request.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.