1263 Rate this article:
No rating

Testing parameters with N_ELEMENTS and !null

Mark Alonzo
The N_ELEMENTS function is typically used to test whether an input parameter has data. For example, here's a program that doubles a number:
function double_it, x
   compile_opt idl2
   on_error, 2

   if n_elements(x) eq 0 then $
      message, 'Need input number to double.'

   return, x*2
end
N_ELEMENTS is used to test whether the user actually passed anything when calling DOUBLE_IT. If not, an error message is thrown:
IDL> a = double_it(4)
IDL> print, a
           8
IDL> b = double_it()
% DOUBLE_IT: Need input number to double.
% Execution halted at: $MAIN$
In IDL 8, we have the option of instead comparing parameters with the null variable!null. In DOUBLE_IT, this looks like:
function double_it, x
   compile_opt idl2
   on_error, 2

   if x eq !null then $
      message, 'Need input number to double.'

   return, x*2
end
Now, which is faster: using N_ELEMENTS or !null? Here's a simple test program:
pro test_nullparameter, param
   compile_opt idl2

   n_iter = 1e7

   t0 = systime(/seconds)
   for i=1, n_iter do a = n_elements(param) eq 0
   t1 = systime(/seconds)
   print, 'N_ELEMENTS:', t1-t0, format='(a15,f12.8,1x,"s")'

   t0 = systime(/seconds)
   for i=1, n_iter do a = param eq !null
   t1 = systime(/seconds)
   print, '!null:', t1-t0, format='(a15,f12.8,1x,"s")'
end
and here's a sample result from my laptop:
IDL> test_nullparameter
    N_ELEMENTS:  1.07800007 s
         !null:  0.84400010 s
It turns out that it's more efficient to compare against !null. The syntax is more compact, too. (Thanks to Jim Pendleton, who initially pointed out this to me.)

Please login or register to post comments.