Ask a question.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kaily
Forum Newbie
Posts: 12
Joined: Fri Jul 05, 2002 12:17 pm

Ask a question.

Post by kaily »

IF you know or have any idea plaese reply.
code1.

Code: Select all

for ($i=0;$i<9119;$i++)&#123;
do_something_here();
&#125;
code2.

Code: Select all

$i=0;
while ($i<9119)&#123;
do_something_here();
$i++;
&#125;
Can code2 instead of code1 anyway?
Which code is faster(or better)?
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

If I had to guess, I'd say the while() loop is slightly faster--since it has a simpler construct. But since this is PHP, the code has to go through the parser, so any performance increase is probably lost by the fact that the while() code has 6 more characters. :)

In any case, if you're concerned about performance, you might consider creating a PHP extension for time-critical functions--but note that this can be a very difficult task.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

If you're worried about speed why not add a bit of code that works out how long it takes to execute (search the forums there's a lot of that about). As for which is better, well the for loop was designed to do the job so why not use it for what it is intended.

Mac
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

FYI--there was an interesting thing I tried. I ran a little performance test on my computer by setting each loop to run 10000000 times, and print one character every time. Since I have PHP stop after 30 seconds, it didn't loop endlessly. I found that the while() loop is actually slightly faster than the other. It produced a 1.50 MB file, and the for() loop only did a 1.35 MB file.
Post Reply