Skip to content
 

Expensive function calls

I know, function calls are not ‘for free’ concerning runtime. This week I discovered that they can be quite expensive. I started with something like the following:

Model “BigCollection” implements something like
def test_something
  big_collection.each do |small_collection|
    small_collection.test_something

Model “SmallCollection” implements something like
def test_something
  small_collection.each do |item|
    item.test_something

And the controller did
inputfile.each do |line|
  collections.each do |bigcollection|
    bigcollection.test_something(line)

Nice, clean, object-oriented programming style. Just because of curiosity I changed it to
items = []
collections.each do |bigcollection|
  big_collection.each do |small_collection|
    small_collection.each do |item|
      items << item
    end
  end
end
...
inputfile.each do |line|
  items.each do |item|
    # here goes the test
  end
end

For testing, I had one “BigCollection” containing 8 “SmallCollections” with a total of about 80 items. On a testfile with about 24.000 lines, the running time decreased from an average of 25 sec to an average of 5 sec!

Leave a Reply

(required)


Refresh