Should I use an associative array or an object?

后端 未结 3 556
别跟我提以往
别跟我提以往 2021-02-01 16:23

As we all know, json_decode gives you the option of returning an associative array or an object. There are many other situations where we have the two options as we

3条回答
  •  面向向阳花
    2021-02-01 17:06

    Performance Benchmark (access time)

    Here is my benchmark. I was mostly interested in access time. I populated an array with 10,000 variables, cast it as an object, then for both the object and array I simply accessed one of the variables 10,000 times. Part of the code:

    $arr = array();
    for( $i=0; $i<10000; $i++ ) {
        $arr['test'.$i] = 'Hello. My name is Inigo Montoya. You killed my father. Prepare to die.';
    }
    $obj = (object)$arr;
    
    $tests = array(0,1000,2000,3000,4000,5000,6000,7000,8000,9999);
    
    foreach( $tests as $test ) {
        $test_name = 'test'.$test;
    
        $start = microtime(true);
        for( $i=0; $i<10000; $i++ ) {
            $var = $obj->$test_name;
        }
        $end = microtime(true);
        $elapsed = $end - $start;
    
        $start = microtime(true);
        for( $i=0; $i<10000; $i++ ) {
            $var = $arr[$test_name];
        }
        $end = microtime(true);
        $elapsed = $end - $start;
    }
    

    Results

    I ran the test multiple times; here is one of the typical result sets; times are in milliseconds.

                Object    Array
    ------------------------------
    test0       4.4880    4.1411
    test1000    4.5588    4.2078
    test2000    4.5812    4.2109
    test3000    4.5240    4.2000
    test4000    4.5800    4.2648
    test5000    4.5929    4.2000
    test6000    4.5311    4.2260
    test7000    4.6101    4.2901
    test8000    4.5331    4.1370
    test9999    4.5100    4.1430
    

    The array was an average of 8.3% faster than the object (7.7% in the set above). The index of the variable we are trying to access has no effect on the access time.

    Seeing the comments above I'm embarrassed to say I'm on PHP 5.3.4.

提交回复
热议问题