Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

Getting rid of inefficient constantize

Trying to improve performance of one controller I’ve found the following:

def application_klass
  @application_klass ||= "application/#{params[:type]}".classify.constantize
end

There are Application::Rental and Application::Bridge models in our rails app, so the method above was used in two places:

  1. application_klass.to_s – to get the model name as a string
  2. application_klass.model_name.human – to get a class name without module prefix

I’ve refactored method in the following way:

def application_klass
  @application_klass ||= "application/#{params[:type]}".classify
end 

And it’s occurrences now looks like this:

  1. application_klass – just call this method to get a model name
  2. application_klass.demodulize – using demodulize to split a string with ::

I’ve got rid of unnecessary constantize method, which is quite inefficient: just imagine that your application tries to find a constant in your project with the name specified in the string. See the benchmarks below to evaluate performance gains:

counter = 100_000
type = 'Rental'

Benchmark.bm(30) do |x|
  x.report('demodulize: ')                   { counter.times { "application/#{type}".classify.demodulize } }
  x.report('constantize.model_name.human: ') { counter.times { "application/#{type}".classify.constantize.model_name.human } }
end

                                     user     system      total        real
demodulize:                      3.560000   0.760000   4.320000 (  4.381891)
constantize.model_name.human:    8.500000   0.070000   8.570000 (  8.601007)
Looking for help? JetRockets has been an leader in Ruby on Rails since 2012. Rails is a core skill for each developer at JetRockets and we'd love to take a look at your project. Contact us and find out how we can help you.