dpv21589 2011-10-26 20:27
浏览 45
已采纳

对于PHP,如果创建新数组或向现有数组添加相同的索引,内存使用会有很大差异吗?

If I am creating an array with several hundred indexes, how much overhead is required for the additional array versus adding a second dimension to an existing array?

I.E. $pages['page']['url'] and $titles['page']['title'] versus $pages['page']['url']['title'] versus $pages['page']['title'], where the last example assumes each index of $pages contains an associative array.

The goal is to be able to be to lookup two attributes of each 'page'. Each 'page' has a 'url' and a 'title', which would be more efficient for memory usage on the arrays? Which for access/storing the data?

Two associative arrays:

// Store the information in arrays
$titles['page1'] = 'Page 1 Title';
$titles['page2'] = 'Page 2 Title';

$urls['page1'] = 'http://www.page1.com';
$urls['page2'] = 'http://www.page2.com';

// Display an example
echo $titles['page1'] . ' is at ' . $urls['page1']; 

or one array of arrays:

$pages['page1'] = array( 'title' => 'Page 1 Title', 'url' => 'http://www.page1.com' );
$pages['page2'] = array( 'title' => 'Page 2 Title', 'url' => 'http://www.page2.com' );

// Display an example
echo $pages['page1']['title'] . ' is at ' . $pages['page1']['url'];
  • 写回答

4条回答 默认 最新

  • du9698 2011-10-26 20:43
    关注

    The memory usage of a two dimensional array is slightly bigger, but this may result from bad code (?).

    <!--
        http://php.net/manual/en/function.memory-get-usage.php
    
        array1: 116408 (1D 1001 keys)     (1x 100.000 keys:  11.724.512)
        array2: 116552 (2D, 1002 keys)    (2x  50.000 keys:  11.724.768)
    
        total:    +144                                             +256
    -->
    
    <?php
    
    function genRandomString() {
        $length = 10;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';    
    
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters))];
        }
    
        return $string;
    }
    
    $i = 0;
    
    // ----- Larger 1D array -----
    $mem_start = memory_get_usage();
    echo "initial1: " . $mem_start . "<br />";
    $arr = array();
    
    for ($i = 1; $i <= 1000; $i++) {
        $arr[ genRandomString() ] = "Hello world!";
    }
    
    echo "array1: " . (memory_get_usage() - $mem_start) . "<br />";
    unset($arr);
    
    // ----- 2D array -----
    $mem_start = memory_get_usage();
    $arr2 = array();
    
    echo "initial2: " . $mem_start . "<br />"; 
    
    
    for ($i = 1; $i <= 500; $i++) {
        $arr2["key______1"][ genRandomString() ] = "Hello world!";
        $arr2["key______2"][ genRandomString() ] = "Hello world!";
    }
    
    echo "array2: " . (memory_get_usage() - $mem_start) . "<br />";
    
    unset($arr2);
    
    unset($i);
    unset($mem_start)    
    echo "final: " . memory_get_usage() . "<br />"; 
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?