From: David Vallner Date: 2006-01-12T11:05:55+09:00 Subject: Re: Looking up properties and speed 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? Is there any speed difference between >these: > >def foo > val = obj.prop > puts val > puts val >end > >def boo > puts obj.prop > puts obj.prop >end > >I assume not because I think the reason it's like that with Javascript >is because of the DOM (yeah, that's not strictly Javascript). > >Cheers > > > Hmm. Accessing the property should be slower, because it involves a method call. BUT! Quite a few guides on coding style would say temporary variables should be avoided whenever possible in clean OO code and replaced with queries (computed property getters). And using a temporary variable only to cheat the interpreter is plain wrong. Avoid. The speed improvement you gain will most likely be next to insignificant, and if not, you still should never optimize without profiling the code first. That said, the code you show is more likely to end up refactored as a method of ``obj'', where you could access the instance variable directly. A method that only manipulates data on another object indeed should be a method of that object. Suggested reading: Martin Fowler's "Refactoring...", a timeless, and IMO highly respected classic. David