Page 1 of 1

array/loop performance improvement?

Posted: Tue Jul 08, 2008 4:23 am
by cathalmccabe
Hello,
I want to read a page, and copy a line of html from it. I want to strip out hyperlinks in the line, so I am starting the loop at a particular point on the line, then checking each 2 characters for "<a".
If I find a link, I ignore the text (until I find ">").

The performance of this code is not good enough as it times out. (Fatal error: Maximum execution time of 30 seconds exceeded in ...)
I can't increase the time.

I have no feel for how long something like this should take. Is the loop too big? Are there any obvious ways to improve performance?

Is there a better way of doing what I am attempting?

Thanks in advance.

Code: Select all

<?php
$lines = file('...');
 
$ignore = 0;
 
// Print each required character, checking for hyperlinks <a and ignoring the link
for ( $counter = 360; counter <= 3380; $counter += 1) {
  if($lines[135][$counter] == "<" && $lines[135][$counter+1] =="a"){
    // check for <a
      $ignore = 1;
  }
  
  if($ignore == 0){
    echo  $lines[135][$counter];
  }else if($lines[135][$counter] == ">"){
  // check for end of ignore
    $ignore = 0;
  }
}
?>
 

Re: array/loop performance improvement?

Posted: Tue Jul 08, 2008 5:08 am
by Eran
check this site for loop optimizations in php - http://www.phpbench.com/

Re: array/loop performance improvement?

Posted: Tue Jul 08, 2008 5:20 am
by dml

Code: Select all

for ( $counter = 360; /*XXX*/counter <= 3380; $counter += 1) {
That could be an infinite loop. Try:

Code: Select all

for ( $counter = 360; $counter <= 3380; $counter += 1) {

Re: array/loop performance improvement?

Posted: Tue Jul 08, 2008 10:53 am
by Christopher
You may want to look into using preg_match instead. I will probably be faster than looping like you are.