From: Robert Klemme Date: 2005-01-20T21:06:00+09:00 Subject: Re: is defined? fast? "Eric Hodel" schrieb im Newsbeitrag news:2068C17C-6A4A-11D9-AFB0-000D93436DA0@segment7.net... > On 19 Jan 2005, at 09:46, Robert Klemme wrote: > > > > > "Eric Hodel" schrieb im Newsbeitrag > > news:12DE17DB-69B1-11D9-AFB0-000D93436DA0@segment7.net... > > > > Looks like the simple var check is better performance wise. > > Personally I > > never felt the need for defined? - only during my initial Ruby stages, > > when I carried some Perl thinking with me; but never after I got rid of > > that. :-) > > module M > def functionality > do_stuff if @x > end > end > > class C > include M > end > > C.new.functionality > > With ruby -w, this will give an 'uninitialized instance variable' > warning. M#functionality needs to be written this way to get rid of > the warning: > > module M > def functionality > @x = default unless defined? @x You can as well do "@x ||= nil" to get rid of the warning. 11:25:49 [otrs-1006999]: ruby -w -e 'class Foo; def x() @bar end end;Foo.new.x' -e:1: warning: instance variable @bar not initialized 13:00:17 [otrs-1006999]: ruby -w -e 'class Foo; def x() @bar ||= nil end end;Foo.new.x' 13:00:34 [otrs-1006999]: > do_stuff if @x > end > end > > Ah, and btw, you don't need the "true if ". Not that it matters > > performance wise since you applied it everywhere - but I prefer to > > reduce > > redundancy... :-) > > I feel it is necessary. You're benchmarking the case of: > > statement if defined? something > > vs. > > statement if $global > > I like being specific. Hm, but as "statement" is the same in both cases you could equally well just benchmark the boolean expression. If you expect effects due to the statement being there then that should probably a realistic statement. Just my 0.02EUR... Kind regards robert