Does really SplFixedArray perform better than arrays?

后端 未结 3 1541
逝去的感伤
逝去的感伤 2021-02-04 10:45

I\'m testing the SplFixedArray building an array with the days of the week, and I get the following results:



        
3条回答
  •  礼貌的吻别
    2021-02-04 11:35

    A SplFixedArray is supposed to be faster than arrays. It doesn't say anything about memory consumption (which is what you're testing here). From http://php.net/manual/en/class.splfixedarray.php:

    "The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation"

    However, using an array of 100000 entries, reveals that it also uses less RAM:

    $users = array();
    for ($i=0;$i<100000;$i++) { 
        $users[$i] = array('id' => rand(), 'name' => 'default');
    }
    echo memory_get_peak_usage(true); //returns 31457280
    

    $users = new SplFixedArray(100000);
    for ($i=0;$i<100000;$i++) { 
        $users[$i] = array('id' => rand(),
                'name' => 'default');
    }
    echo memory_get_peak_usage(true); //return 26738688
    

提交回复
热议问题