From: Ryan Leavengood Date: 2006-01-14T00:05:00+09:00 Subject: Re: Looking up properties and speed On 1/11/06, Jonathan Leighton wrote: > Hi, > > In Javascript, if one were to use the same property value twice or more, > one would store it in a local variable because looking up the property > slows things down. > > Is the situation the same in Ruby? In almost any language method calls will be slower than directly accessing a variable. I did a quick benchmark with my "quickbench" utility (I'll release it one of these days), and here are the results: ------------------------------------------------------------------------- | QuickBench Session Started | | 3000000 Iterations | ------------------------------------------------------------------------- user system total real 1. test.foo == other_var 2.547000 0.000000 2.547000 ( 2.407000) 2. var == other_var 1.688000 0.000000 1.688000 ( 1.595000) ------------------------------------------------------------------------- | Fastest was <2. var == other_var> | ------------------------------------------------------------------------- So the method call it about half as fast, which isn't that bad. Here is the code: require 'quickbench' class Test attr_reader :foo def initialize(foo) @foo = foo end end test = Test.new('something') val = test.foo other_val = 'blah' QuickBench.go(3000000, 25) {} __END__ test.foo == other_val val == other_val