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):
- When available use the built-in classes and methods, rather than rolling your own;
- Use Regular Expressions rather than costly loops, when you need to parse and process all but the smallest text;
- Use Libxml rather than the slower REXML if you are processing XML documents;
- 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);
- 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;
- Simplify and reduce nested if/unless as much as you can and remember that the operator ||= is your friend;
- 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.
0 comments:
Post a Comment