473,395 Members | 1,624 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

for loop speed trick?

Hi,

In the Yahoo! UI event.js file I see the following quite a bit

for (var i=0,len=unloadListeners.length; i<len; ++i) {

when I always just write

for (var i=0; i<unloadListeners.length; ++i) {

Is it worth it to declare the variable len to save time evaluating
unloadListeners.length?

Thanks,
Peter

Aug 31 '06 #1
14 1896
On 31 Aug 2006 16:49:30 -0700, pe**********@gmail.com wrote:
>In the Yahoo! UI event.js file I see the following quite a bit

for (var i=0,len=unloadListeners.length; i<len; ++i) {

when I always just write

for (var i=0; i<unloadListeners.length; ++i) {

Is it worth it to declare the variable len to save time evaluating
unloadListeners.length?
Yes it is.

Jim.
Aug 31 '06 #2
Jim Ley wrote:
>Is it worth it to declare the variable len to save time evaluating
unloadListeners.length?
Yes it is.
IIF your array length isn't expected to change during the iteration.

Also, unless you iterate quite a number of times, you are unlikely to see
any observable benefit. Iterating 0..10, for example, will probably not
realize any noticeable speed improvement.

See also this interesting thread on loop speed:
http://groups.google.com/group/comp....ecf5e28064c78c

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Sep 1 '06 #3
JRS: In article <11*********************@b28g2000cwb.googlegroups. com>,
dated Thu, 31 Aug 2006 16:49:30 remote, seen in
news:comp.lang.javascript, pe**********@gmail.com posted :
>In the Yahoo! UI event.js file I see the following quite a bit

for (var i=0,len=unloadListeners.length; i<len; ++i) {

when I always just write

for (var i=0; i<unloadListeners.length; ++i) {

Is it worth it to declare the variable len to save time evaluating
unloadListeners.length?
It will save time. But, unless the loop body is small and will be
executed many times, the saving will be small in proportion to the
total.

If the operations in the loop can be performed in the reverse order,

i = unLoadListeners.length ; while (i--) { loop body }

should be a little faster still.

It is better not to use "i" as an identifier in code that others may
read; in some fonts it looks like I j l 1, and may be resented by
grammar-checkers.
You should rarely need to ask questions about the comparative speeds of
equivalent pieces of code, since it is so easy to do the test yourself.

It's a good idea to read the newsgroup and its FAQ.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 2 '06 #4
Dr John Stockton wrote:
i = unLoadListeners.length ; while (i--) { loop body }
It is better not to use "i" as an identifier in code that others may
read;
It is a convention across many languages to use i while iterating over
arrays, etc.

Straying from that convention may cause more confusion than someone who
can't tell letters apart...

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Sep 2 '06 #5
Hi,

Matt Kruse wrote:
Dr John Stockton wrote:
> i = unLoadListeners.length ; while (i--) { loop body }
It is better not to use "i" as an identifier in code that others may
read;


It is a convention across many languages to use i while iterating over
arrays, etc.

Straying from that convention may cause more confusion than someone who
can't tell letters apart...
Which languages??? In all the languages I use, the convention is rather
to avoid using one letter variables. In fact, it's generally recommended
to avoid using abbreviations at all. They make the code harder to read
and to maintain.

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Sep 2 '06 #6
Hi,

Lee wrote:
The "i" index variable is not an abreviation. It is a standard that
goes back at least to FORTRAN, where it was the first of the default
Integer variables.
Still, using one letter names for variables is really not recommended or
recommendable.

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Sep 2 '06 #7
Laurent Bugnion wrote on 03 sep 2006 in comp.lang.javascript:
Lee wrote:
>The "i" index variable is not an abreviation. It is a standard that
goes back at least to FORTRAN, where it was the first of the default
Integer variables.

Still, using one letter names for variables is really not recommended or
recommendable.
A meaning, not a fact.

My personal feeling is, that one letter variables are ideal for code parts
that are close together, as often is with a loop or a small function.

function product(x,y){
return x*y;
};

much better than:

function product(firstVariable,secondeOne){
return firstVariable * secondeOne;
};

In modular programming this is often the case.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 2 '06 #8
Hi,

Evertjan. wrote:
Laurent Bugnion wrote on 03 sep 2006 in comp.lang.javascript:
>Still, using one letter names for variables is really not recommended or
recommendable.

A meaning, not a fact.
I guess you mean "an opinion". You're right. I actually meant "not
recommendable" only. Guidelines are, in the end, matter to interpretations.
My personal feeling is, that one letter variables are ideal for code parts
that are close together, as often is with a loop or a small function.

function product(x,y){
return x*y;
};

much better than:

function product(firstVariable,secondeOne){
return firstVariable * secondeOne;
};

In modular programming this is often the case.
I won't lie, I use one-letter variables occasionally. I help to write
guidelines (one of many activities) in my job as software engineer, for
example the C# guidelines and the JavaScript guidelines that we used in
our last project (a Web application). And yet I sometimes consciously
write code that hurts the guidelines. It's OK as long as you do it
consciously and as long as you document it. However, using one letter
variables just because they were used in fortran doesn't sound like a
good reason to me. Programming languages change, and guidelines change
with them too. The example which comes in mind is Microsoft using polish
notation before, and recommending against it now. I continue to use
polish notation (I have many reasons which make me prefer it) in my
private projects, but I don't use it at work.

Anyway... One could talk about guidelines for hours. For now, I should
rather hit the sack ;-)

Lauren
Sep 2 '06 #9
Dr John Stockton wrote:
You should rarely need to ask questions about the comparative speeds of
equivalent pieces of code, since it is so easy to do the test yourself.
What is the best way to benchmark speeds?

Thanks,
Peter

Sep 2 '06 #10
wrote on 03 sep 2006 in comp.lang.javascript:
Dr John Stockton wrote:
>You should rarely need to ask questions about the comparative speeds of
equivalent pieces of code, since it is so easy to do the test yourself.

What is the best way to benchmark speeds?
There is no "best way" in programming.
Only taste and result.
Mostly taste for John, and many others, I presume.

However storing time before the action, and comparing it with the time
after it, looping the action if the time is small, will get you there.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 3 '06 #11
Hi,

Lee wrote:
Laurent Bugnion said:

>>However, using one letter
variables just because they were used in fortran doesn't sound like a
good reason to me.


In my part of the world, putting words into people's mouths is
considered to be quite rude. I didn't suggest the fact that
the index variable "i" was used in FORTRAN as a reason to use
it.
You are right. I have somehow amalgamated Matt's and your posts into
one. I certainly didn't intend to be rude. Apologies.
I was responding to your claim that all of the languages
you use somehow discourage the use of single character names.
That's still true. I thankfully never had to use Fortran.
In fact, every programming language manual that I can lay hands
on, from FORTRAN to Java, includes sample code that makes use
of single character loop indices (usually "i") in cases where
the index has no other meaning.
And I am talking about guidelines, not manuals. See my previous post
about that.

Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Sep 3 '06 #12
JRS: In article <ed*********@news4.newsguy.com>, dated Sat, 2 Sep 2006
15:22:57 remote, seen in news:comp.lang.javascript, Matt Kruse
<ne********@mattkruse.composted :
>Dr John Stockton wrote:
> i = unLoadListeners.length ; while (i--) { loop body }
It is better not to use "i" as an identifier in code that others may
read;

It is a convention across many languages to use i while iterating over
arrays, etc.

There is a convention, descending from FORTRAN, to use the letters I to
N to start the names of integer variables, and the other letters for
those of floats - but that's convenient only when the code calls for a
compatible mix of integers and floats.

That is not infrequently modified to have I..N starting the names of
counting variables, with the others as other variables, without regard
to whether the latter have integer or general values.

J K I are often used for counters, and N M L for ranges-of-count - also
only when convenient - with that being the general order of preference.

Short-name variables are appropriate for short-range purposes in code,
where it's easier to remember that J is the current counter and what it
represents than it is to type countOfHungryTabbyCats consistently -
especially in a language where variables do not have to be explicitly
declared.

In primitive times, when the ASR33 ruled as an I/O device, there was no
reason to avoid using I as a variable name; it could not be confused
with i or l or j (non-existent), nor with 1 in the available font; and
programming material was rarely mixed with ordinary text. But nowadays,
a code author generally does not know what fonts the code may later be
presented in - especially if it gets in News or on the Web.

Another reason for preferring not to use I as a variable concerns its
effect on searching files with Ctrl-F or similar; the word may also
occur in HTML text or in Javascript strings or comment either as a
capital letter or a Roman numeral.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 3 '06 #13
Hi,

Dr John Stockton wrote:

<snip>
Short-name variables are appropriate for short-range purposes in code,
where it's easier to remember that J is the current counter and what it
represents than it is to type countOfHungryTabbyCats consistently -
especially in a language where variables do not have to be explicitly
declared.
That's where you got to love Intellisense and other similar
technologies, though unfortunately its use is limited with JavaScript.

<snip>
Another reason for preferring not to use I as a variable concerns its
effect on searching files with Ctrl-F or similar; the word may also
occur in HTML text or in Javascript strings or comment either as a
capital letter or a Roman numeral.
Absolutely.

<snip>

Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Sep 3 '06 #14
In article <44********@news.bluewin.ch>, Laurent Bugnion
<ga*********@bluewin.chwrites
>Hi,

Dr John Stockton wrote:

<snip>
>Short-name variables are appropriate for short-range purposes in code,
where it's easier to remember that J is the current counter and what it
represents than it is to type countOfHungryTabbyCats consistently -
especially in a language where variables do not have to be explicitly
declared.

That's where you got to love Intellisense and other similar
technologies, though unfortunately its use is limited with JavaScript.
<snip>

People are so used to

for (var i = 0; ...

that they recognise it immediately, whereas

for (var index = 0; ...

makes them spend time looking at it twice, and

for (var nMyOuterIndex = 0; nMyOuterIndex < max; ++nMyOuterIndex)
arr[nMyOuterIndex] = "";

makes them scream with outrage.

John
--
John Harris
Sep 5 '06 #15

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

Similar topics

29
by: Bart Nessux | last post by:
Just fooling around this weekend. Wrote and timed programs in C, Perl and Python. Each Program counts to 1,000,000 and prints each number to the console as it counts. I was a bit surprised. I'm not...
12
by: Steve | last post by:
Hi, I'm getting some output by running a command using os.popen. I need to parse the output and transform it in some sense so that it's 'DB compatible', (i.e I need to store the output in a...
15
by: RAYYILDIZ | last post by:
I Know C is the fastest progrmming language. However, by using some bitwise operation you can get faster the your program. For instance, we talk about swap function. For a integer swapping we use...
3
by: deko | last post by:
Problem: why doesn't this With block work? is it possible to have a For Each loop within a With block? With objWord .Documents.Add Template:=strTemplate, NewTemplate:=False, DocumentType:=0...
22
by: Jan Richter | last post by:
Hi there, the Code below shows DJBs own implementation of strlen (str_len): unsigned int str_len(char *s) { register char *t; t = s; for (;;) { if (!*t) return t - s; ++t;
16
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of...
19
by: vamshi | last post by:
Hi all, This is a question about the efficiency of the code. a :- int i; for( i = 0; i < 20; i++ ) printf("%d",i); b:- int i = 10;
8
by: SaltyBoat | last post by:
Needing to import and parse data from a large PDF file into an Access 2002 table: I start by converted the PDF file to a html file. Then I read this html text file, line by line, into a table...
2
by: alireza6485 | last post by:
Hi, Could you please rewrite the program for me?I tried my best and the program still does not do what it has to do. I have to write a code that generates random speed and distance .it ask the...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...

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.