Bruce Duncan wrote:
I have been starting to use Javascript a lot lately and I wanted to
check with the "group" to get your thoughts on code efficiency.
First, is there a good site/book that talks about good and bad ways
to code.
The reason I ask is because I was just thinking about the
following...whi ch is better and/or why?
document.forms["myform"].elements["txtname"].value
or
document.myform .txtname.value
There is more to efficiency than execution speed alone, though
javascript is inevitably not particularly fast in execution (being
interpreted) so speed of execution is worth considering. But Time taken
(or wasted) in maintenance contributes to efficiency, of a different
sort.
I prefer the longer form accessor syntax because it is self-documenting.
Given:-
document.myform
- it is not immediately obvious whether the object referred to is a
form, and image, and embed, an applet, an expando property of the
document, etc (assuming the form name does not make that obvious, as
"myform" probably would). While:-
document.forms['myform']
- is clearly intended to refer to a form object, and -
document.imgaes['myform'] - is clearly intended to refer to an IMG
element. The coinciding observation that the longer, collections based,
accessor is W3C DOM standard and back compatible with every browsers
known to understand javascript and forms, just adds weight to this
decision.
The longer accessor must be slower to resolve, but how significant that
is would be directly related to how often it needs to be resolved. Given
a desire to repeatedly refer to the same form control I would be
inclined to assign a reference to that control to a local variable on
the first occasion it was needed and then make subsequent references
relative to that variable:-
var formControl = document.forms["myform"].elements["txtname"];
formControl.val ue = 'something';
// etc.
Or, if the desire was to access different controls in the same form then
a reference to the form (or more likely its - elements - collection)
could be assigned to the local variable:-
var formElements = document.forms["myform"].elements;
formElements['txtname'].value = 'something';
// etc.
(Or, better yet, pass a function a reference to the form/elements
collection/form control as an argument so it doesn't need to be resolved
against the DOM at all.)
So it isn't the type of accessor used that contributes to, or detracts
from efficiency; if it is only used once to resolve a reference to a
form or its controls then the fractionally faster resolution of the
"shortcut" accessor becomes insignificant if presented with any
advantages associated with the longer, more formal, accessors.
Richard.