KBD

Keith Devens .com

Thursday, November 20, 2008 Flag waving
May you live in interesting times – Ancient chinese proverb
← Data Binding in .NETArgument passing runaround →

Daily link icon Saturday, December 6, 2003

Neat for loop idiom

Just came across a neat for loop idiom I don't think I'd ever considered before:

for(long i = 0, m = file.length(); i < m; i++)

As a general rule, it's bad (with varying degrees of badness) to call a function in a loop condition. One of my favorite examples of why is exemplified by this bit of C:

for(n=0; n<strlen(str); n++)
    print str[n];

It turns what should be a Theta(n) algorithm into a Theta(n^2) algorithm.

Usually what I'd do in that case is something like (back to Java):

int length = file.length(); // or str.length, etc.
for(int n=0; n<length; n++){...}

But the idiom above allows you to put it in the loop declaration, which allows you to better associate it with the loop conceptually, and has the added benefit of making the variable scoped to the loop.

← Data Binding in .NETArgument passing runaround →

Comments XML gif


Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

November 2008
SunMonTueWedThuFriSat
 1
2345678
9101112131415
16171819202122
23242526272829
30 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 4 posts

Recent comments XML

new⇒Java join function

Meh, don't have null strings in​your string arrays imo, but you're​welcome ...

Keith: Nov 19, 7:51pm

Girls, please don't get breast implants

sorry but another thing i have to​make a comment on about you​men...the men...

happynow: Nov 17, 11:36pm

Books by Vincent Cheung

to all Cheung​fans:

read:

http://www.progin​osko.com/aquascum/cheung.h...

Zamir: Nov 16, 9:07am

Spider solitaire

To undo or not to undo that is the​question.
I'm an undoer. 
My dad​was n...

Can Turk: Nov 15, 2:50pm

Generated in about 0.178s.

(Used 8 db queries)

mobile phone