Re: [xsl] the fastest way to test if variable is empty

Subject: Re: [xsl] the fastest way to test if variable is empty
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxxx>
Date: Wed, 08 Dec 2004 11:36:37 -0500
Dusan,

It's a bit difficult to say what's the "fastest way" as different processors implement things differently, so what's fastest depends on much more than simply what kind of expression you use.

That having been said, the test "string($variable)" will test true if the string has any characters in it, false if it equals ''.

This is the same as seeing if it has length zero, except that it doesn't have to turn the variable into a string and then measure its length and then test to see whether that is zero. It only turns it into a string and then checks to see whether the string has any value. So it may be faster, at least in micro time.

The test "$variable", if $variable is bound to a node-set, will test true if there are any nodes in the node set, which it probably is for you, hence what you are seeing (it's always true).

"string($variable)", when $variable is a node-set, will cast $variable to a string first (by taking the string value of the first node in the set in document order), before casting it to a Boolean true() or false().

If you want to test false for " " (that is, a string that contains only whitespace), use "normalize-space($variable)", which does the same, except collapsing whitespace while doing so.

"string($variable)" and "normalize-space($variable)" are probably the XSLT-idiomatic ways to do this. No measuring of string lengths is necessary: that's just a habit people have learned elsewhere.

But I would not be surprised if an implementation were to optimize the test "string-length($variable)=0" to "string($variable)" when compiling, so you would see no difference in speed. Don't know whether Xalan-J does this, however.

Cheers,
Wendell

At 10:20 AM 12/8/2004, you wrote:
Hi all.

Can anybody tell me the fastest way, how to test, if variable contains some
text or number?

For now, i am using test "string-length($variable)=0", but seems not to be the
fastest.


Somebody tells me to use test "$variable", but with my XalanC, it seems to be
true everytime.

Thanks.

PS. variable can't contain nodes, it may contains only alphabetics or numbers
and whitespaces.


======================================================================
Wendell Piez                            mailto:wapiez@xxxxxxxxxxxxxxxx
Mulberry Technologies, Inc.                http://www.mulberrytech.com
17 West Jefferson Street                    Direct Phone: 301/315-9635
Suite 207                                          Phone: 301/315-9631
Rockville, MD  20850                                 Fax: 301/315-8285
----------------------------------------------------------------------
  Mulberry Technologies: A Consultancy Specializing in SGML and XML
======================================================================

Current Thread