Get Into the Performance Mind-set

Ruby optimization is more about rethinking what the code does and less about finding bottlenecks with specialized tools. The major skill to learn is rather the right way of thinking about performance. This is what I call the Ruby Performance Mind-set.

How do you get into this mind-set? Let me give you a hint. When you write code, remember that memory consumption and garbage collection are, most likely, why Ruby is slow, and constantly ask yourself these three questions:

  1. Is Ruby the right tool to solve my problem?

    Ruby is a general-purpose programming language, but that doesn’t mean you should use it to solve all your problems. There are things that Ruby is not so good at. The prime example is large dataset processing. That needs memory: exactly the sort of thing that you want to avoid.

    This task is better done in a database or in background processes written in other programming languages. Twitter, for example, once had a Ruby on Rails front end backed by Scala workers. Another example is statistical computations, which are better done with, say, the R language.

  2. How much memory will my code use?

    The less memory your code uses, the less work Ruby GC has to do. You already know some tricks to reduce memory consumption—the ones that we used in our example: line-by-line data processing and avoiding intermediate objects. I’ll show you more in subsequent chapters.

  3. What is the raw performance of this code?

    Once you’re sure the memory is used optimally, take a look at the algorithmic complexity of the code itself.

Asking these three questions, in the stated order, will get you into the Ruby Performance Mind-set. And then you may begin to find that new code that you write is fast right from the start, without any optimization required.

Ah, but what can you do about an old program? What problems should you look for? It turns out that the majority of performance problems come from a relatively limited number of sources. In the next chapter we’ll talk about these, and how to fix them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.164