Jump to content

Speed Question


ZachMEdwards

Recommended Posts

Which do you guys think is faster?

$fp = fsockopen($host, 80) or die("$errstr ($errno)");
fwrite($fp, $this->headers($method, $file, $host, $referer, $data));
for($a=0,$r='';!$a;) { #option 1
$b = fread($fp,8192);
$r.=$b;
$a=(empty($b) ? 1 : 0);
}

or

$fp = fsockopen($host, 80) or die("$errstr ($errno)");
fwrite($fp, $this->headers($method, $file, $host, $referer, $data));
$r=''; #option 2
while(!feof($fp))
$r .= fgets($fp,256);

and why? According to my tests, it looks like option 2 is faster. I'm curious as to why...

 

And is there a faster alternative? As you can see in the code, I'm using fwrite on a fsocket. I need this to be as fast as possible!

Link to comment
https://forums.phpfreaks.com/topic/203289-speed-question/
Share on other sites

Seems logical to me. There are a lot more calcualtions/assignements going on in option A.

 

Option A:

- The for loop must do a check of var $a on each iteration

- The fread operator is used

- An assignment is made to the var $b

- a concatenation is made on the var $r

- A ternary operator is used to make an assignement to the var $a

 

Option B:

- a check is made on each iteration to see if the end of file is reached

- fgets() is run

- a concatenation is made on the var $r

 

By the way, running a ternary operator on each iteration in option A is less efficient than doing a single IF statement because an assignment must be made on each iteration. I aslo don't know whay you would use 0 and 1 for the values instead of a boolean true/false. Then you could have done this:

$a=empty($b);

 

A more efficient approach would be to assign $a before the loop and jsut use a single IF statement. Then if the condition is false that code is never run. Additionally, for heaven's sake, give your variables descriptive names. Using $a, $b, $r just makes maintenance and debugging much harder.

 

Link to comment
https://forums.phpfreaks.com/topic/203289-speed-question/#findComment-1065084
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.