Save Memory

The first step to make your application faster is to save memory. Every time you create or copy something in memory, you add work for GC. Let’s look at the best practices to write code that doesn’t use too much memory.

Modify Strings in Place

Ruby programs use a lot of strings, and copy them a lot. In most cases they really shouldn’t. You can do most string manipulations in place, meaning that instead of making a changed copy, you change the original.

Ruby has a bunch of “bang!” functions for in-place modification. Those are gsub!, capitalize!, downcase!, upcase!, delete!, reverse!, slice!, and others. It’s always a good idea to use them as much as you can when you no longer need the original string.

chp2/string_in_place1.rb

Get Ruby Performance Optimization now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.