Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: [[ -n $v ]] versus (( $#v > 0 ))



"Nikolai Weibull" wrote:
> What does the (imaginary) Zsh Scripting Style Guide say about
> 
> if [[ -n $v ]]; then
>   ...
> fi
> 
> versus
> 
> if (( $#v > 0 )); then
>   ...
> fi

I tend to use the former because it strikes me as more straightforward.
I'm "really" testing "is the string given by this parameter substitution
non-empty" rather than "is the number that I get by inquiring about the
length of the value stored in this parameter a positive one".

As this indicates, I don't think there's much more to this in practice
than psychology, so I wouldn't lose much sleep over it.

> Which version is "faster"?

I suppose the computer scientist's answer is that the second is faster
since there's no operation proportional to the size of the string stored
in the parameter v.

That's already a bit fishy when you think about why you might be testing
to see if the parameter is empty.  It's more likely to be a case of
"did I set this variable to 'yes' earlier on, or didn't I?" rather
than "does this string contain the complete works of Shakespeare, or is
it empty?"

In most cases the practical difference is likely to be tiny since
there's so much else going on in the shell to do with command handling and
substitution.

Internally, the second form goes through a full math evaluation which
includes a parameter substitution (which happens not to have to copy the
string---unless the string is huge that's a minor effect if you look at
all the goings on in subst.c:paramsubst(), which I advise against)
whereas the first one does a standard parameter substitution and looks
at the first byte of the result.  So the first is probably
faster in a lot of cases, but, again, the difference is typically
trivial and it's entirely possible some difference I haven't thought of
dominates.

-- 
Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR PLC, Churchill House, Cambridge Business Park, Cowley Road
Cambridge, CB4 0WZ, UK                          Tel: +44 (0)1223 692070



Messages sorted by: Reverse Date, Date, Thread, Author