KBD

Keith Devens .com

Tuesday, October 7, 2008 Flag waving
I was always told, that if I ain't gonna be part of the greatest, I gotta be the greatest... – Busta Rhymes
← Keeping our promises (or... Long Live Iraq!)Dates and times on my site →

Daily link icon Friday, July 2, 2004

For loop idioms

Everyone knows the standard for loop idiom:

for($n=0; $n<@arr; $n++) #...

It turns out there are a few more idioms that people use. First, usually you want to cache the upper bound to avoid having to calculate it every time. That's not as important for a language like Perl or PHP where scalar(@arr) or count($arr) or strlen($str) is a quick operation, but it's very important for something like strlen(str) in C:

for(int n=0,int c=strlen(str); n<c; n++) //...

Another one is the following, which works nicely if you want to count backwards:

for($n=@arr-1; $n--;) #...
← Keeping our promises (or... Long Live Iraq!)Dates and times on my site →

Comments XML gif

Aggelos wrote:

It is important for PHP too. Say, give it a 1000000 loops without pre-calculation and with pre-calculation. And compare the results. Of course there is no difference if you have 10 or 100 loops. But for big numbers, the difference is quite noticeable.

∴ Aggelos | 2-Jul-2004 11:42am est | #4898

Ehud (http://lambda-the-ultimate.org) wrote:

Jon Bentley has a nice column on profileers, with the running example of calculating prime numbers. Amusingly when I translated the code to Ada the problem with recalculating the sqrt each iteration disappeared...

∴ Ehud | 2-Jul-2004 11:54am est | http://lambda-the-ultimate.org | #4899

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)
:

October 2008
SunMonTueWedThuFriSat
 1234
567891011
12131415161718
19202122232425
262728293031 



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⇒Timesheet Calculator

Hadn't seen it before now, but my​company already uses a time​tracking prog...

Keith: Oct 7, 10:44am

Girls, please don't get breast implants

Hey everyone, 

I am new to this​blog and I have enjoyed reading all​your...

Sarah.M.: Oct 6, 9:45am

obout inc - ASP.NET controls

I like there components. I've got​it to work locally on my pc.​However I'm ...

Jeff: Oct 2, 4:43pm

Dumb substring behavior in C# (and Java)

Yes, the Substring function is not​helpful when you hit the length​problem,...

Mike Irving: Oct 2, 7:56am

Generated in about 0.252s.

(Used 8 db queries)

mobile phone