Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to call function in a nested way or to split each passage inside a var?

Tags:

php

Take these three examples:

ONE

return lowercaseKeys(json_decode(trim($json),true));

TWO

$trimmed = trim($json);
$array = json_decode($trimmed,true);
$return = lowercaseKeys($array);
return $return;

THREE

$return = trim($json);
$return = json_decode($return,true);
$return = lowercaseKeys($return);
return $return;

Aside from readability, which is the best performance wise? What is considered best practice?

p.s. code is only an example, not related to the question, I just copy pasted from my notepad window.

like image 659
0plus1 Avatar asked Feb 11 '11 14:02

0plus1


2 Answers

Number one rule is do whatever is most readable when dealing with micro-optimizations. But here is a small test I did.

<?php
$iterations = 1000000;
$tests = array('one', 'two', 'three');
$json = json_encode($tests);

foreach ($tests as $function) {
        echo $function;
        $start = microtime(true);
        for ($i = 1; $i <= $iterations; $i++) {
                $function($json);
        }
        $end = microtime(true);
        echo ' - ' . ($end - $start) . " sec\n";
}

function one($json) {
        return array_change_key_case(json_decode(trim($json),true), CASE_LOWER);
}
function two($json) {
        $trimmed = trim($json);
        $array = json_decode($trimmed,true);
        $return = array_change_key_case($array, CASE_LOWER);
        return $return;
}
function three($json) {
        $return = trim($json);
        $return = json_decode($return,true);
        $return = array_change_key_case($return, CASE_LOWER);
        return $return;
}
?>

Results:

one - 3.3994290828705 sec
two - 3.5148930549622s sec
three - 3.5086510181427s sec

Option one is indeed a tiny bit faster, but that was one million iterations, and the time difference still wouldn't even be noticeable. With smaller amounts of iterations, the timing is too variable to even have a pattern to declare one better than the other.

like image 189
Mike Avatar answered Oct 30 '22 17:10

Mike


Option 1 will be maybe a microsecond faster than the other 2 options and use a few bits less physical memory, but any difference will be completely negligible unless multiplied on an exponential level. The core here is going to be the ultimate readability. I find Option 1 to be perfectly suitable personally, but I recognize that in some of the teams where I work, this option would not meet the standard for the lowest common denominator of developer. Option 2 and Option 3 really are exactly the same since you're not doing anything with the extra variables that are created. They both create 3 separate tokens. Option 2 is more explicitly readable in that the variables describe the method being applied at that stage, so I would vote for 2 as well.

like image 32
Joel Etherton Avatar answered Oct 30 '22 18:10

Joel Etherton