From: Sven Johansson Date: 2006-01-02T01:12:55+09:00 Subject: Re: A few questions of function and style from a newbie Robert Klemme wrote: > A simple test shows that there is indeed significant overhead attached to > method invocations - if methods perform simple tasks. The relative overhead > of course depends on the work the method performs. I for my part would > always start with a modularized version and only inline methods if this is > actually a cure for a performance problem. There is a famous quote about > premature optimization... Heh. But how can we know if it premature unless we have an idea about how inefficient method calls are? :) Nevertheless, you point is well taken. > #! /usr/bin/env ruby > > require 'benchmark' > > REP = 1_000_000 > > def foo(n) 0 + n end > > Benchmark.bmbm(10) do |bm| > bm.report("direct") do > REP.times { x = 0 + 1 } > end > > bm.report("method") do > REP.times { x = foo(1) } > end > end > > > Rehearsal --------------------------------------------- > direct 1.188000 0.000000 1.188000 ( 1.201000) > method 2.156000 0.000000 2.156000 ( 2.166000) > ------------------------------------ total: 3.344000sec > > user system total real > direct 1.187000 0.000000 1.187000 ( 1.217000) > method 2.172000 0.000000 2.172000 ( 2.234000) > > $ ruby -e 'puts 2.172000 / 1.187000' > 1.82982308340354 Ah, interesting. And a fine exemple of how to use the internal benchmarking support for us Ruby newbies. More to the point, it shows that it isn't so bad - I was thinking of order-of-magnitude losses, and here is merely a factor two or so, and that's for essentially empty method bodies... it will do. :) > Happy new year! To you as well! /Sven