[ LiB ]Language StructureSummary

Memory, Performance, and Speed

Ruby suffers from the same speed impediment as the other languages in this bookbeing interpretive and-high level. Ruby's built-in profiler tool helps quite a bit when gauging performance by examining code snips and routines for slowdowns. The profiler can be called from the command line by adding r profile, or it can be used inside code by using require, like so:

require "profile"

The profile library will print a summary of the number of calls to each Ruby method in the given program and the time spent in each method. This is all printed to $stdout.

Garbage Collection

Ruby has a mark and sweep garbage collection system. It periodically sweeps through dynamically allocated memory and reclaims it if it isn't in use. Ruby also provides a GC (garbage collection) module for interfacing the underlying garbage collection methods, which include

Speed

Finally, here are a number of tricks you can use to help speed up Ruby code:

Check the profiler to see where the code is bogging down.

Use the built-in GC to take control over garbage collection.

Initialize variables before they are used. Variables used within a block can be defined before the interpreter hits the block.

When iterating over a large set of elements, declare any iterator variables.

When returning variables from a block, have the variables pre-initialized so they aren't allocated on-the-fly.

Ruby supports both multiple threads and forks for creating sub-processes. Threads are implemented within the interpreter, and forks are invoked in the operating system. Either of these can be used for a speed hit in certain cases.

[ LiB ]Language StructureSummary