Lasse Reichstein Nielsen wrote:
Richard Cornford wrote:
An alternative to safe execution with the comparison
operation could be:-
if((new String(f[i].nodeName)).toL owerCase() == 'input')
While it's probably not hurtfull in any way, you never need
to create a new String object explicitly. Exactly the same
effect would be achieved by
if ((String(f[i].nodeName)).toL owerCase() == 'input')
Yes, the end result would be identical.
Behind the scenes, there might be created a new String
object anyway, in order to call it's toLowerCase method,
That is what ECMA 262 says happens when a method of a string object is
called on a string primitive.
but an intelligent Javascript interpreter
should be able to optimize that away (should
such one exist).
Yes, implementations may optimise any aspects of ECMA 262, they are only
required to behave (or appear to behave) as if they were following the
specification. But it is extremely difficult to tell which are
optimising what, and how. And in the cross-browser scripting world we
should not be too interested in optimisations that may only apply to
some implementations .
I just don't like to see "new String(...)" :)
And I don't mind seeing it when it is serving some purpose. Certainly
whenever I am planning to call more than three or so String methods on a
single string primitive I will usually explicitly convert it into a
String object (so that it is not necessary for the interpreter to do so
internally for each method call).
As a method of rendering a questionable, but probably string type,
property safe for the application of String methods I wouldn't argue
that passing the property's value through the String constructor called
as a function is equally effective. But as the language specification
says that an intermediate String object is created I see the explicit
construction of a String object as no more than rendering apparent what
should be expected to be happening anyway. (By 'expected' I mean that an
understanding based on the spec should expect that to be happening
conceptually, not that the interpreter actually has to be doing it.)
Maybe it is just a matter of personal bias, with my predominantly OO
programming experience numbing me to the sight of just another object
being constructed and your (I would guess) greater experience of
functional programming (certainly greater than mine) leaving you
preferring to see functions used. Or is there something more tangible
that can be said against the use of the object constructor?
You have probably guessed that I am not buying the efficiency due to
possible optimisation argument. And would counter by pointing out that
by the spec the implied String object creation will mean one extra call
to the internal ToString method with your version. Though as that call
is passing ToString a string primitive argument, which will just be
returned unaltered, the difference would be expected to be negligible.
Richard.