Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize an if else if statement where previous ifs are not used in loop?

Tags:

php

This is hypothetical code, assuming I have the following:

Let's say I have an array and it has lots of data, integers in this sample question, but it can ANY type of data that's already sorted in some fashion in regards to the if statements.

$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,...,9,9,9);

Let's say I have a for loop with numerous if else if statements, and those can have any criteria for doing something.

for($i=0; i<count($a); i++) {
    // these if statements can be anything and may or may not be related with $a
    if($a[$i] == 0 && $i < 10) { 
        // do something
    }
    else if($a[$i] == 1 && $i < 20) {
        // do something
    }
    else if($a[$i] == 2) {
        // do something
    }
    else if($a[$i] == 3) {
        // do something
    }

    // and so on
}

Now the question, after the first if statement iterations are done, it's never used. Once the for loop starts using the next if statement, the previous if statement(s) don't need to be evaluated again. It can use the first if statement n amount of times and so on and so forth.

Is there a way to optimize it so it doesn't have to go through all the previous if else if statements as it's looping through the data? Mind, the data can be anything, and the if statements can be any variety of conditions.

Is there a paradigm shift, that I don't see, that is required on how this should be coded up to provide optimal performance?

like image 207
rotaercz Avatar asked Nov 01 '22 16:11

rotaercz


1 Answers

You could leverage call_user_func_array. You would need to build a class that stored the methods to call to perform the statements. Consider a class like this:

class MyStatements {
    public function If0($a, $i) {
        if($a[$i] == 0 && $i < 10) {
            // do something
        }
    }

    public function If1($a, $i) {
        if($a[$i] == 1 && $i < 20) {
            // do something
        }
    }
}

you could then do something like this:

$stmts = new MyStatements();
for($i = 0; i < count($a); i++) {
    call_user_func_array(array($stmts, 'If' . strval($i)), array($a, $i));
}
like image 142
Mike Perrenoud Avatar answered Nov 09 '22 09:11

Mike Perrenoud