22 Juni 2007

PHP-Schleifen: Fataler Anfängerfehler

Immer wieder sehe ich schleifen die folgendermaßen aufgebaut sind:

for($i=0; $i < count($array); $i++) { ... }

das ist so aber garnicht so sinnvoll, denn dabei wird das array bei jedem Durchlauf erneut durchgezählt. Das ganze zu Lasten der Performance. Besser man macht es so:

$max = count($array);
for($i=0; $i < $max; $i++) { ... }

hier wird die Anzahl der Array-Elemente nur einmal gezählt.

Labels: ,

5 Kommentare:

Anonymous Lars meinte...

... oder gleich mit rein in die Schleife:
for($i=0, $max = count($array); $i < $max; $i++) { ... }

22. Juni 2007 16:15  
Blogger Felix Goldstein meinte...

stimmt ;-)

22. Juni 2007 17:25  
Anonymous Anonym meinte...

wenn überhaupt, dann aber
for ($i=1; $max = count($a), $i<$max; $i++)


dieses konstrukt läuft aber deutlich langsamer, als die beiden vorab gepoststen solution.

greetings,
chris

19. Juli 2007 10:41  
Anonymous Anonym meinte...

Wie wäre es ganz einfach mit der foreach-Schleife?
Wesentlich effizienter und kürzer. :-)

2. Oktober 2007 12:27  
Anonymous Anonym meinte...

This is my first post I'd love to congratulate you for such a terrific quality forum!
thought this is a perfect way to make my first post!

Sincerely,
Sage Brand
if you're ever bored check out my site!
[url=http://www.partyopedia.com/articles/mardi-gras-party-supplies.html]mardi gras Party Supplies[/url].

10. Januar 2010 20:53  

Kommentar veröffentlichen

Links zu diesem Post:

Link erstellen

<< Startseite