Performance Tip In Ruby

Today performance is what that comes first, both from the end-user perspective and from developers point of view. So in this blog, I’ll be covering some simple things which we developers should follow, in order to optimize performance of our ruby code.

Here are the some tips with there benchmarking result:

  • Always use string interpolation instead of string concatenation
  language = "ruby" do |x| {p "testing string, "<< language} {p "testing string, #{language}"}

  [#<Benchmark::Tms:0x000000000b271388 @cstime=0.0, @real=6.565399962710217e-05, @cutime=0.0, @label="", @stime=0.0, @total=0.0, @utime=0.0>,
   #<Benchmark::Tms:0x000000000b270b40 @cstime=0.0, @real=4.6490000386256725e-05, @cutime=0.0, @label="", @stime=0.0, @total=0.0, @utime=0.0>]

From the above benchmarking, we can see that string concatenation operation is slower than the string    interpolation operation.

  • In ruby destructive operations are faster, we all know destructive operations are risk prone, as they modify the actual value, instead of modifying the copy. But if we have such use-cases where, we want to modify the actual object, than we should go for this destructive ones
  hash1 = {"color": "blue", height: 100}
  hash2 = {"width": 200} do |x| {hash1.merge(hash2)} {hash1.merge!(hash2)}

  [#<Benchmark::Tms:0x000000000b090078 @cstime=0.0, @real=7.367998478002846e-06, @cutime=0.0, @label="", @stime=0.0, @total=0.0, @utime=0.0>,
   #<Benchmark::Tms:0x000000000b08f880 @cstime=0.0, @real=3.569999535102397e-06, @cutime=0.0, @label="", @stime=0.0, @total=0.0, @utime=0.0>]

As we can see from the above benchmarking, destructive operations are nearly two times faster than the normal operations.

  • Parallel Assignments are slower than the normal assignment do |x| {var1,var2 = 1, 2}   #parallel assignment {var1 = 1; var2 = 2} 

  [#<Benchmark::Tms:0x000000000a2d59d8 @cstime=0.0, @real=8.679999154992402e-06, @cutime=0.0, @label="", @stime=0.0, @total=0.0, @utime=0.0>,
   #<Benchmark::Tms:0x000000000a2d5230 @cstime=0.0, @real=5.723002686863765e-06, @cutime=0.0, @label="", @stime=0.0, @total=0.0, @utime=0.0>]

Just look at the above benchmark output, it justifies that parallel assignments are slower.

  • Magic statement in Ruby:  frozen_string_literal

In ruby, we know that strings are mutable, what does that even mean?

In order to understand this, Let’s take an example:

  hash1 = {"width": 200}
  def get_width

In the above code, whenever get_width will be accessed, it will always allocate memory for the string “width”. so, in order to solve this, ruby introduced the concept of “freeze”, now calling the above code like this will solve the problem.

  def get_width

But using freeze, everywhere with strings, will makes our code unclean and not DRY.
So, for this Ruby 2.3 introduced MAGIC COMMENT, termed as frozen_string_literal.

When we add this magic comment “frozen_string_literal” to any ruby file, all the strings within that file will be treated as immutable resulting in improving our code performance.

  # frozen_string_literal: true

  hash1 = {"width": 200}
  def get_width

For more information like this, stay tuned 🙂



Today Performance is what that comes first, when we developers try to develop web services. One of the issue is that, when a web service tries to interact with database, in order to get the result it may take time depending on the number of records.


For this blog, I am assuming that you have knowledge about Rails and basic idea about Redis.

Getting Started

Lets’s imagine we are building a back-end for the online movie app. Customers will use this app to view all the movies, their details, resulting in huge load on Database. So what if we could reduce the load on the database by caching the movies data. But for caching what should we use ?

There comes REDIS to our rescue.


Redis is the key-value store, which we can use for CACHING to speed things up and improve our performance.

But Redis is not just a plain key-value store, it is data structures server, means it not just limited to support strings as value, but also more complex data structures, such as Hashes, Lists, Sets, Sorted Sets. For detailed information refer this.


Strings are the most basis data type that we use for caching in Redis. They are binary safe and easy to use. So we mostly go for them.

But in our scenario Strings DataType was not enough as I have to store the whole list of movies and their respective details in Redis.  Strings work well, but it stores the whole list in the string format as value. So, before sending the data , I have to parse them in JSON Format,  such that they can be used by the views in order to present it to the User. But what if the data is huge, parsing strings to JSON or any other required format will be time consuming. So, string is not which can be used in our case.

By reading these memory optimization blog and documentation, I found that there is other Datatype that Redis supports, which can be helpful i.e, Hashes.


Hashes are the perfect data structure to represent the objects. They are the map between string fields and string values. Also, they are stored in attribute: value format, just like how the tables data is mapped to object using ActiveRecord in Rails. Small hashes are encoded in a very small space, so we should always try to represent our data using hashes.

And in this way using hashes our data parsing issue is solved. Now, we fetch data, as it is from Redis using Hashes, and there is no conversion of data format is involved.

Also memory consumption, reading and writing performance can be improved using optimized storage of hashes over strings data type.

Now lets check the above theory using Benchmark in rails. Here, we are going to use  redis-namespace and redis service which is explained later in this section.

Setting Data in Redis: do |x|
  #here data is in the json format

  #Setting data using hash(value will be stored as hash) { Event).set_list(key: CMS_MOVIE_LIST, data: data) }

  #Setting data using string(value will be stored as string) { Event).set(key: MOVIE_LIST, data: data) }

#user     system   total    real
#0.030000 0.010000 0.040000 ( 0.011480) #Hashes
#0.150000 0.000000 1.150000 ( 0.447619) #Strings

Fetching Data from Redis: do |x|

  #Fetching data using hash(value will be stored as hash) { Event).get_list(key: CMS_MOVIE_LIST) }

  #Fetching data using string(value will be stored as string) { Event).get(key: MOVIE_LIST) }

#user     system   total    real
#0.010000 0.000000 0.010000 ( 0.008200) #Hashes
#0.090000 0.000000 0.090000 ( 0.032398) #Strings

This demonstrates, how our performance can be improved by using Hashes over Strings in Redis.

So in order to use the same things in our rails application, we are going to use redis-namespace. For detailed information about this, refer Redis::Namespace

Initializing Redis in Rails

We instruct our rails app to use redis as a cache store and set the redis_host in ENV variable like this:

REDIS_HOST: 'redis://localhost:6379'

Now, initialize a wrapper around redis using redis-namespace. Or have a service redis_service.rb using redis-namespace so that we can interact with our redis.

class RedisService
  def initialize(klass:)
    redis = ENV['REDIS_HOST'], timeout: 1)
    @namespaced_redis =, redis: redis)

  def set(key:, data:, expire: nil)
    #Command to Set value of a key
    @namespaced_redis.set(key, data.to_json)

    #Expire your redis key In 1 week
    @namespaced_redis.expire(key, 1.weeks)

  def set_list(key:, data:, expire: nil)
    #Command to Set List of Data on a Redis Key
    @namespaced_redis.set(key, Marshal.dump(data))

  def get(key:)
    #Command to Get only Value of Key in Json Format

  def get_list(key:)
    #Command to Get List of Data from Redis

  def del(key:)
    #Command to delete Key from Redis

  def keys(pattern: nil)


In the above code, we are using marshal. It is a library in ruby which converts the collection of Ruby objects into byte stream. It is the fastest option available in ruby for data serialization. For detailed information refer this

Now we have generic Redis Service which we can use to perform different operations like add, delete, fetch data from Redis in our rails application.

Advantages of writing this service class:

  •  Code is DRY
  • All the redis commands are there in it, and we can use them whenever and wherever we want in our rails app.

Now, we are going to use this, to fetch movies on the basis of city.

Managing Redis Cache in Rails

Here, the whole idea is that, when a customer wants list of movies in a particular city, firstly we are going to fetch the movies, by directly quering on database. Secondly, we will cache the response using redis-namespace wrapper, such that on subsequent quering, the data will be fetched from redis, and not from the Database, thus improving our application performance.

class MoviesController &lt; ApplicationController
  #Here we are going to use the RedisService to perform operations on redis
  def index
    #Check if the list of movie is there in redis
    movies = Movie).get_list(key: "movies:#{params[:city]}")

    #If there is no movies in redis
    if movies.blank?
      #Load Movies from Database

      #serialize the data
      movies = serialize_resource(movies, V1::MoviesSerializer)

      #Cache the serialized response in Redis, so that it can be used again Movie).set_list(key: "movies:#{params[:city]}", data: movies, expire:

    #Returns the response
    mobile_success_response(data: movies)

The above code is perfect, but there is one loophole in that, if any movie is added or it is updated in the database, it will not be shown to the customer if the data is fetched from Redis.

So in order to solve the above issue, what we have to do ?

We’ll write a callback in such a way that, whenever any movie is added or updated,  we will delete the keys corresponding to movie list. So, during updation of any movie, if User wants the data, it will be fetched directly from database and then will be stored in redis cache. On the subsequent calls, it will be fetched from redis. Below is the callback, to achieve this:

class Movie < ApplicationRecord
  after_commit :update_in_redis, on: [:create, :update]
  after_commit :delete_from_redis, on: [:destroy]

  def update_in_redis
    redis = self.class)

    #Delete all the keys matching the movies: pattern
    redis.del(key: redis.keys(pattern: "movies:*"))

  def delete_from_redis
    redis = self.class)

    #Delete a movie from redis if it is deleted from database

Hope this blog will be useful. For more information like this, Stay tuned 🙂

Feature Testing Using Capybara

Feature testing is high level testing that allows us to go through our entire system, ensuring that each and every component is working perfectly fine. The test-cases written for it are termed as feature specs, which requires capybara.

In this blog, we will be focussing on writing feature specs using capybara with rspec. More specifically, we are going to look at capybara key features as well as, how capybara specs looks like.

We as a developer are mainly focussed about the underlying things, but we should also consider end user’s view. So, Capybara comes to rescue, it lets you write yours test-cases from user’s perceptive i.e, how end users would interact with your system. It is a ruby gem build on the top of underlying web-based driver and these drivers drive our browsers based on what our master ‘capybara’ says.

There are multiple web-drivers supported by capybara, some of these are as follows:

  • rack:test

    Capybara supports this web-driver by default. It is a library that sits above the rack app, and allows to fake web-requests to the app as a result making it considerably faster than other web-drivers because in reality we haven’t started a server. But it lacks JavaScript support.

  • selenium-webdriver

    It is one of the most popular driver and by default it supports Firefox browser where we can actually visualize our tests. It uses browser’s Javascipt Engine making it feel like having a actual human Q/A department interacting with our system. Also, we can configure it to be used in headless-mode which is specifically good from time and CI perspective.

  • capybara-webkit

    This one is comparatively faster than selenium-webdriver as it doesn’t load our entire app and also supports JavaScript, making it useful for true headless testing. It depends on Qt, a cross platform development toolkit. For more information, you can refer this capybara-webkit and Qt.

  • poltergeist

    This one runs our test-cases in PhantomJS browser with full JavaScipt support. It decreases the overall testing time by reducing the number of dependencies needed by CI server. But to use this, our system must have PhantomJS installed. Also, TravisCI, CircleCI have PhantomJS preinstalled. For more information you can refer poltergeist and phantomjs.


Provided you have installed Ruby, Rails and Rspec, we have to install Capybara. Here we will be using poltergeist driver which depends on PhantomJS, so firstly we need to have PhantomJS.

  • Installing PhantomJS


     brew install phantomjs


     sudo port install phantomjs
  • Installing Capybara and Poltergeist

    Add this to Gemfile and run bundle install.

     gem 'capybara'
     gem 'poltergeist'

    After installing it, we need to tell our RSpec that we want to use Capybara with Poltergeist by adding this to spec/rails_helper.rb:

     # load up Capybara
     require 'capybara/rspec'
     require 'capybara/rails'
     # load up Poltergeist
     require 'capybara/poltergeist'
     #Capybara.javascript_driver = :other_web_driver
     Capybara.javascript_driver = :poltergeist  

    If we want to use web-driver other than poltergeist, we can include that here in place of poltergeist in the above mentioned file. But if we do not specify any capybara driver, than by default it will use rack::test.

Application Example

As we have already installed everything, lets move onto how to write feature specs using capybara?

Consider a scenario, where our app has a home page and on that page we have a Log in button, so when a already registered user clicks on that Log in button she/he should be taken to a dashboard page.

Let’s test this feature using capybara:

require 'rails_helper'

RSpec.feature "Log In" do
  background do
    @user = create :user, email: ''

  scenario "signing in with valid credentials", js: true do
    visit '/homes'
    expect(page).to have_link('Log in')
    within(".login") do
      click_link 'Log in'

    within(".sign-up") do
      fill_in 'Email', with:
      fill_in 'Password', with: 'testpassword'
      click_button 'Log In'
    expect(page).to have_text('Dashboard page')

Here, we have used js:true to tell capybara that it has to use JavaScript driver for this test-case, otherwise if we don’t mention, it will by default use rack::test

One of the problem that I have faced when using Capybara with Rspec is that sometimes my test-cases were passing, while other times they were failing. So after searching I found that the main cause was because when we have feature spec with Capybara’s JavaScript driver, in that case the app-under-test and specs does not share a database connection. So, the solution is to use DatabaseCleaner truncation strategy instead of transaction one.

In order to use DatabaseCleaner, we have to include this in our Gemfile and run bundle install:



group :test do
 gem 'database_cleaner'

After that, we have to configure our DatabaseCleaner strategy in spec/rails_helper.rb:

RSpec.configure do |config|
  config.use_transactional_fixtures = false

  config.before(:suite) do

  config.around(:each) do |example|
    DatabaseCleaner.strategy = :truncation

    # Start transaction do

      # Run example

There are many ways as well as frameworks for doing end-to-end testing, one is using capybara with rspec which we have already covered in this blog. We can also do this testing using minitest that I’ll be covering in my next blog. Stay tuned 🙂