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.)
There is a difference in functionality too, N_ELEMENTS(obj) would call the _overloadSize function if obj were an object that inherited from IDL_Object.
Whoops, meant:
An empty list is a valid object, though, so it’s not null.
Exactly, but N_ELEMENTS is 0, which makes for a confusing situation if you are not familiar with the new operator overloading.
I agree it’s more compact. But, faster!? I suppose, if you are calling your function 10 million times, as here. But, if I were doing that, I would have already written the damn thing in C! If speed is what you are worried about, I think I would focus on the graphics system. That could use a little speed up, I think!
Pingback: 引数チェック時の N_ELEMENTS と !NULL のパフォーマンス | TAKA's Lunch BOX