1316 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.)
MOST RECENT

Remote Sensing of Hydrocarbon Microseepage

8/6/2018

Remote sensing can help professionals in the oil and gas industry discover new areas for exploration. One... more »

GISCafe Interviews Harris Geospatial's Rebecca Lasica at the 2018 Esri UC

8/2/2018

GIS Cafe – August 1, 2018 GISCafe interviews Rebecca Lasica, Director of Enterprise Platforms and... more »

SIGN UP & STAY INFORMED

Sign up to receive the latest news, events, technologies and special offers.

SIGN ME UP