From: Eric Hodel Date: 2005-01-19T09:29:37+09:00 Subject: Re: is defined? fast? --Apple-Mail-11--1061695470 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; format=flowed On 18 Jan 2005, at 15:24, Mark Hubbart wrote: > On Mon, 17 Jan 2005 22:26:17 +0900, George Moschovitis > wrote: >> Hello everyone, I have a simple question: >> >> is 'if defined?(MyFlag)' as fast as 'if $my_flag' >> or is it much slower? > > A quick check suggests that defined? *might* be just slightly slower. > But probably not enough to matter. You may want to profile your > scripts (just "require 'profile'" at the top) and see what's best in > your case. No, profile cannot detect a global test or defined? being called, because they are not method calls. You want to use benchmark.rb. defined? MyFlag is at best almost half as fast as $my_flag, probably because defined? does not just return true (it returns a String). $ cat x.rb require 'benchmark' TIMES = ARGV.shift || 100_000 $x = true @x = true @@x = true module X; X = true; end Benchmark.benchmark do |bm| bm.report "baseline " do end bm.report "defined? Nested::Constant" do TIMES.times do true if defined? X::X true if defined? X::Y end end bm.report "defined? Constant " do TIMES.times do true if defined? Benchmark true if defined? NoSuchConst end end bm.report "defined? $global " do TIMES.times do true if defined? $x true if defined? $y end end bm.report "defined? local " do TIMES.times do true if defined? bm true if defined? no_such_local end end bm.report "defined? @var " do TIMES.times do true if defined? @x true if defined? @no_such_ivar end end bm.report "defined? @@var " do TIMES.times do true if defined? @@x true if defined? @@no_such_cvar end end bm.report "$global " do TIMES.times do true if $x true if $y end end end $ ruby x.rb baseline 0.000000 0.000000 0.000000 ( 0.000046) defined? Nested::Constant 0.680000 0.000000 0.680000 ( 0.884762) defined? Constant 0.370000 0.000000 0.370000 ( 0.458034) defined? $global 0.320000 0.000000 0.320000 ( 0.336950) defined? local 0.330000 0.000000 0.330000 ( 0.345521) defined? @var 0.370000 0.000000 0.370000 ( 0.455369) defined? @@var 0.370000 0.000000 0.370000 ( 0.400793) $global 0.150000 0.000000 0.150000 ( 0.174302) -- Eric Hodel - drbrain@segment7.net - http://segment7.net FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04 --Apple-Mail-11--1061695470 content-type: application/pgp-signature; x-mac-type=70674453; name=PGP.sig content-description: This is a digitally signed message part content-disposition: inline; filename=PGP.sig content-transfer-encoding: 7bit -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) iD8DBQFB7am7MypVHHlsnwQRAlHMAJ47Aqo0w2c6RtXr3+MgJi3Xz1DeBACgyWpT lBwFzKljsEjWCtdbIXYOYAI= =85s1 -----END PGP SIGNATURE----- --Apple-Mail-11--1061695470--