Optimize your Ruby code

This may seem obvious, but a Rails application is essentially ruby code that will have to be run. Make sure your code is efficient from a Ruby standpoint. Take a look at your code and ask yourself if some refactoring is in order, keeping in mind performance considerations and algorithmic efficiency. Profiling tools are, of course, very helpful in identifying slow code, but the following are some general considerations (some of them may appear admittedly obvious to you):

  1. When available use the built-in classes and methods, rather than rolling your own;
  2. Use Regular Expressions rather than costly loops, when you need to parse and process all but the smallest text;
  3. Use Libxml rather than the slower REXML if you are processing XML documents;
  4. Sometimes you may want to trade off just a bit of elegance and abstraction for speed (e.g. define_method and yield can be costly);
  5. The best way to resolve slow loops, is to remove them if possible. Not always, but in a few cases you can avoid loops by restructuring your code;
  6. Simplify and reduce nested if/unless as much as you can and remember that the operator ||= is your friend;
  7. Hashes are expensive data structures. Consider storing the value for a given key in a local variable if you need to recall the value a few times. More in general, it’s a good idea to store in a variable (local, instance or class variable) any frequently accessed data structure.

Permanent link to this article: https://blog.openshell.in/2010/11/optimize-your-ruby-code/

Leave a Reply

Your email address will not be published.