【问题标题】:Array taking up waay too much memory数组占用太多内存
【发布时间】:2012-05-23 15:28:54
【问题描述】:

我正在创建一个数组来保存从查询返回的值 - 似乎添加到多维数组会导致脚本占用多达 125Mb 的内存,并且考虑到数组应该保存的数据总量并不多超过 5Mb 这很奇怪:

这是我正在做的事情:

try 
{
    if (!$link = mysql_connect(DB_Host, DB_User, DB_Password))
            Throw New Exception(mysql_error());
    if (!mysql_select_db("Spexplus_Demo"))
            throw New Exception(mysql_error());
} 
catch (Exception $e) 
{
    echo $e->getMessage().$e->getTraceAsString();
    exit(1);
}

$query = "select cda.categoryid as categoryId, 
                  cda.templatetype as templateType, 
                  hn.headerid as headerId, 
                  hn.name as headerName, 
                  an.attributeid as attributeId, 
                  an.name as attributeName
                  from categorydisplayattributes cda 
                  join categoryheader ch on cda.headerid = ch.headerid 
                  and cda.templatetype = ch.templatetype 
                  and cda.categoryid = ch.categoryid 
                  join headernames hn on cda.headerid = hn.headerid 
                  and hn.localeid = 1
                  join attributenames an on cda.attributeid = an.attributeid 
                  and an.localeid = 1";

$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))

        {
            $categorydisplayattributes[$row['categoryId']][$row['templateType']][$row['headerId']][$row['headerName']][$row['attributeId']][$row['attributeName']] =array() ;
        }


echo "Memory After CDA:".memory_get_usage(TRUE).Line_Terminator;
exit();

当我检查时,查询结果本身不会超过 5Mb 左右,但是,以这种方式将值分配给数组会导致峰值 - 还有其他人遇到过这样的事情吗?

【问题讨论】:

  • 我非常盲目的猜测是因为它是一个 6 维哈希表。
  • 尝试使用 ini_set('memory_limit', '512M') 添加内存
  • nikic.github.com/2011/12/12/… ling告诉你PHP数组有多大

标签: php arrays memory


【解决方案1】:
    while($row = mysql_fetch_assoc($result))


           {

//concatenate the values using '.' if string 

$index = $row['categoryId']][$row['templateType']][$row['headerId']][$row['headerName']][$row['attributeId']][$row['attributeName'];

                $categorydisplayattributes[$index] =array() ;
            }

试试看。

【讨论】:

  • 下降到一半,但仍然很高 - 数组通常会/应该需要这么多内存吗?
  • 索引有多长 + 数组大小是多少?如果您可以考虑将其拆分成块,也会提高性能和记忆力。如果您可以粘贴输出样本将有助于深入思考
  • array(1082) { [10200]=> array(2) { [0]=> array(4) { [35]=> array(1) { ["General Information"]=> array(10) { [3411896]=> array(1) { ["Manufacturer"]=> array(0) { } } [341450]=> array(1) { ["Manufacturer Part Number"]=> array(0) { } } [341451]=> array(1) { ["Manufacturer Website Address"]=> array(0) { } } [34113319]=> array(1) { ["Brand Name"]=> array(0) { } } [3412389]=> array(1) { ["Product Line"]=> array(0) { } } 这是数组的一个样本 - 我这样做的原因是我需要保持订单不变
  • 如果是这种情况,我认为尝试创建一个临时表并使用索引键将上述记录插入其中,然后使用索引作为键查询表,这将保存 php 数组以保存此临时数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2013-07-18
  • 2013-07-11
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
相关资源
最近更新 更多