Efficiency of PHP arrays cast as objects?

前端 未结 3 1917
花落未央
花落未央 2021-01-15 20:00

From what I understand, PHP stdClass objects are generally faster than arrays, when the code is deeply-nested enough for it to actually matter. How is that eff

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 20:31

    function benchmark($func_name, $iterations) {
        $begin = microtime(true);
        for ($i = 0; $i < $iterations; $i++) {
            $func_name();
        }
        $end = microtime(true);
    
        $execution_time = $end - $begin;
    
        echo $func_name , ': ' , $execution_time;
    }
    
    function standClass() {
        $obj = new stdClass();
        $obj->param_one = 1;
        $obj->param_two = 2;
    }
    
    function castFromArray() {
        $obj = (object)array('param_one' => 1, 'param_two' => 2);
    }
    
    
    benchmark('standClass', 1000);
    benchmark('castFromArray', 1000);
    
    benchmark('standClass', 100000);
    benchmark('castFromArray', 100000);
    

    Outputs:

    standClass: 0.0045979022979736
    castFromArray: 0.0053138732910156
    
    standClass: 0.27266097068787
    castFromArray: 0.20209217071533
    

    Casting from an array to stdClass on the fly is around 30% more efficient, but the difference is still negligible until you know you will be performing the operation 100,000 times (and even then, you're only looking at a tenth of a second, at least on my machine).

    So, in short, it doesn't really matter the vast majority of the time, but if it does, define the array in a single command and then type-cast it to an object. I definitely wouldn't spend time worrying about it unless you've identified the code in question as a bottleneck (and even then, focus on reducing your number of iterations if possible).

提交回复
热议问题