Last Updated: February 25, 2016
·
595
· thehappycoder

Remember about types in ruby or it will bite you

At first I would like to justify ruby and say that this is the common problem of languages with dynamic type system

Recently I've been working on one rails application and noticed big slowdown (about 7-8 seconds) on particular page. After a while I discovered the cause -- the NewtonRaphsonIrrCalculator class (https://code.google.com/p/irr-newtonraphson-calculator/downloads/list)

Profiling revealed masses of BigDecimal#coerce calls. The class was doing all calculations with this type, although if you see the source you won't find any references of BigDecimal. So where the BigDecimal came from? From here:

def self.calculate(flows, max_iterations=100, initial_guess=nil)

The flows array was consisting of BigDecimal instances.

So I thought that maybe it makes sense to perform all calculations inside NewtonRaphsonIrrCalculator with BigDecimals to avoid #coerce calls. Well, that didn't make much of a difference. It still took about 6 seconds.

In the end I decided to convert flows array to array of floats

def cash_flows=(cash_flows)
  @cash_flows = cash_flows.map {|flow| flow.to_f}
end

Now calculate method takes less than a second and the output is the same. Yay! So, the conclusion is -- the types matter and neglecting them can cost you performance and memory problems.