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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.