473,549 Members | 2,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

code efficient

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

Just looking for some insight.

TIA
-Bruce
Jul 23 '05 #1
8 3712
I believe the second looks quite efficient.

Since the first one has to get the object from the array (searching for
the object).
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

Just looking for some insight.

TIA
-Bruce


Jul 23 '05 #2
Bruce Duncan wrote:
which is better and/or why?
document.forms["myform"].elements["txtname"].value
or
document.myform .txtname.value


I did a rough timing test (see code below) and the different in execution
time is minimal. I had to execute the loop 100,000 times just to see a
..9seconds difference.

I would say the preferred way to reference elements is always:
document.forms["myform"]["txtname"].value

because:
1) It doesn't rely on global references to a form, and is easy to read
2) You can replace the strings with variable references at a later time with
no problems or confusion
3) php users can replace the field name with txtname[] if they wish, without
causing errors

I got this result on the test file below:
3905
3976
3015

<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT>
function timeit() {
var max = 100000;
var start = new Date();
for (var i=0; i<max; i++) {
var val = document.forms["myform"]["txtname"].value;
}
var stop = new Date();
var m1 = stop.getTime() - start.getTime() ;

var start = new Date();
for (var i=0; i<max; i++) {
var val = document.myform .elements["txtname"].value;
}
var stop = new Date();
var m2 = stop.getTime() - start.getTime() ;

var start = new Date();
for (var i=0; i<max; i++) {
var val = document.myform .txtname.value;
}
var stop = new Date();
var m3 = stop.getTime() - start.getTime() ;

alert(m1+"\n"+m 2+"\n"+m3);
}
</SCRIPT>
</HEAD>
<BODY onLoad="timeit( )">

<form name="myform">
<input type="text" name="txtname" value="123">
</form>

</BODY>
</HTML>

--
Matt Kruse
Javascript Toolbox: http://www.mattkruse.com/javascript/
Jul 23 '05 #3
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

Just looking for some insight.


I'd use:

var field = document.getEle mentById('txtna me0);
field.value = 'bla';

Berislav

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.
Jul 23 '05 #4
"Bruce Duncan" <bruce~w~duncan @~hotmail.com> writes:
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


The former is better for one, very important, reason: It is correct
according to the W3C DOM.

The latter assumes that the form element object is a property of the
document object, with the same name as the form.

For all current browsers, that is almost always the case (one
exception is Gecko browsers in standards mode and where the form has
only an id-attribute and no name-attribute - then the form is still
part of the forms collection, but not a property of the document
object).

However, there is no guarantee that future browsers will all honor
this tradition of polluting the document object (I hope they won't,
it's really annoying - try making a form with id="body"!)

The former is both correct according to standards, meaning it will
almost certainly work in all future browsers, *and* will work in all
Javascript enabled browsers since Netscape 3 (Netscape 2 didn't allow
access by name, only by number).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5
Ivo
> "Bruce Duncan" writes:
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

"Lasse Reichstein Nielsen" wrote The former is better for one, very important, reason: It is correct
according to the W3C DOM.

The latter assumes that the form element object is a property of the
document object, with the same name as the form.


For the sake of efficiency only, complying with the W3C DOM can hardly be an
argument.
However, if a script encounters document.forms["myform"] , it immediately
knows where to look for myform, while document.myform will make it look
for myform in every branch until it finds it in the forms collection.
Ivo
Jul 23 '05 #6
Balaji. M. wrote:

<--top posting fixed-->
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

Just looking for some insight.

The "best" way, for that is the first one. As its more "cross-browser"
and allows for ID's to be used instead of NAME's in the elements.
I believe the second looks quite efficient.

Since the first one has to get the object from the array (searching for
the object).


Yes, the second is technically "faster", but it has its flaws. Both ways
do though.

Read the FAQ with regards to top-posting.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq/
Jul 23 '05 #7
Berislav Lopac wrote:
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...w hich is better and/or why?

document.form s["myform"].elements["txtname"].value
or
document.myfo rm.txtname.valu e

Just looking for some insight.

I'd use:

var field = document.getEle mentById('txtna me0);
field.value = 'bla';

Berislav


And then wonder why it breaks in certain browsers? NN4.xx comes to mind
first. I am sure there are more, especially IE4, since it doesn't
support getElementById (natively anyway)
--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq/
Jul 23 '05 #8
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.
Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
3068
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class has two int memebers "dataA", "dataB". The derived class has an additional int member "dataC". I am simply trying to overload the + operator so that...
3
1988
by: Axter | last post by:
I'm wondering about the practical use of dynamic_cast in reusable or generic code. I'm currently working on a smart pointer that can be used on vector and other STL containers. See following link: http://code.axter.com/arr_ptr.h In above code, there's a function called clone_func_ptr_interface within the func_ptr_holder class. In this...
2
8465
by: Vance M. Allen | last post by:
Greetings, I am establishing a database for the purpose of logging access to my secure webserver and am wanting to make the database as efficient as I can because it will be doing a lot of work when the site goes live. What is the most efficient way in a MySQL table to store remote IP addresses? What data type should I use? Should I...
12
1460
by: Michael Culley | last post by:
I found this code in a project: StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM SomeTable") .Append("WHERE SomeField = SomeValue") .Append("ORDER BY etc etc etc") at first I thought it was using a using statement but it's not. It works because sb.Append returns an instance of itself. I'd be interested to hear what...
10
1376
by: storyGerald | last post by:
Recently, I'm interested in writing very efficient code. Problem: there is a sequence { a(0), a(1), ..., a(n-1) } and a very small positive integer k, write an algorithm without using multiply to calculate the following formula: n-1 _____ \ \ ki
19
2517
by: Marco | last post by:
FYI: Guidelines for writing efficient C/C++ code http://www.embedded.com/showArticle.jhtml?articleID=184417272 any comments?
48
2584
by: Tony | last post by:
How much bloat does the STL produce? Is it a good design wrt code bloat? Do implementations vary much? Tony
19
1876
by: santanu mishra | last post by:
Hi , I am stuck with a requirement from my client to change the date format from mm/dd/yy to dd/mm/yy .If any body can help me out with this regard as its very much urgent. Regards, Santanu
13
1407
by: fulio pen | last post by:
I have following page: http://www.pinyinology.com/test/testGet.html Part of the code is: javascript: document.getElementById("moon1").innerHTML ="moon"; document.getElementById("moon2").innerHTML ="moon"; document.getElementById("moon3").innerHTML ="moon";
25
15523
by: Abubakar | last post by:
Hi, recently some C programmer told me that using fwrite/fopen functions are not efficient because the output that they do to the file is actually buffered and gets late in writing. Is that true? regards, ...ab
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7715
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5087
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1935
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1057
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.