On Mon, 17 Jan 2005 22:26:17 +0900, George  Moschovitis
<george.moschovitis / gmail.com> 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.

These results might be affected by caching of data; if you use
different variables for each of the 5000 checks, it could easily come
out different.

mark@eMac% ruby -rprofile  
def a  
  5000.times{true if defined? Foo}
end
def b
  5000.times{true if $foo}
end

a
b

  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 95.92     0.47      0.47        2   235.00   235.00  Integer#times
  2.04     0.48      0.01        1    10.00    10.00  Profiler__.start_profile
  0.00     0.48      0.00        1     0.00   230.00  Object#b
  0.00     0.48      0.00        1     0.00   490.00  #toplevel
  0.00     0.48      0.00        2     0.00     0.00  Module#method_added
  0.00     0.48      0.00        1     0.00   240.00  Object#a

cheers,
Mark