简体   繁体   中英

How can I make these loops faster?

I'm using PHP4 for a project I'm working on. I had to expand this code (which works fast enough for the data at hand):

for ($i = 1; $i <= count($arr); $i++) {
$a = $arr[$i]['date'];
    for ($y = 1; $y <= 10000000; $y++) {
      $c = $arr[$i]['data'][$y];
      // here I inserted another loop
    }
}

I inserted another loop in it, like so:

for ($k = $i + 1; $k <= count($arr); $k++) {
    $next_is_empty = false;
    $next_is_null = false;
    if ($arr[$k]['data'][$y] == '') {
        $next_is_empty = true;
        break;
    } elsif (is_null($arr[$k]['data'][$y])) {
        $next_is_null = true;
        break;
    }
}

The code is more a general idea then a specific working code, since I'm writing by memory. However, I think it is accurate enough for my questions. So, this loop I inserted works fine for most cases, but is too slow in some - how could I speed it up? I'm also curios about general rules of performance based on this example. I know that nested loops are better to be avoided, but why for example does the code works fast enough if I put the variables $next_is_empty/null in front of my loop (then the solution is wrong, but fast enough)? I know it needs to make more reassignments, but how come they take so much time?

do not use count() in the loop , make the count() in different line and then use the variable in the loop

$count =  count($arr);
for ($i = 1; $i <= $count; $i++) {
$a = $arr[i]['date'];
    for ($y = 1; $y <= 10000000; $y++) {
      $c = $arr[i]['data'][y];
      // here I inserted another loop
    }
}

this way have better bench-marking result

the point of defining the variable $next_is_empty outside the loop, it difficult to answer as - as far as i know- it depends on the PHP version you use, but better to put the outside , that is the original.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM