场景如下:数据库里有大量记录,php程序需要取出来做一些运算,是一次取出所有还是一次取出部分?示例代码如下:

//一次读取
$start = '2012-06-11 00:00:00';
$end = '2012-06-18 00:00:00';
$rows = $db->query("select ... where
        time between '$start' and '$end'");
foreach ($rows as $row) {
    $name = $row["name"];
    $table[$name] = $row["value"];
}

//多次读取
$start = '2012-06-11 00:00:00';
$end = '2012-06-18 00:00:00';
$start_t = strtotime($start);
$end_t = strtotime($end);
$time_span = 43200;
for ($t = $start_t; $t < $end_t; $t += $time_span) {
    $this_s = date("Y-m-d H:i:s", $t);
    if ($t + 86400 > $end_t) {
        $this_e = date("Y-m-d H:i:s", $end_t);
    } else {
        $this_e = date("Y-m-d H:i:s", $t + $time_span);
    }
    $rows = $db->query("select ... where
            time between '$this_s' and '$this_e'");
    foreach ($rows as $row) {
        $name = $row["name"];
        $table[$name] = $row["value"];
    }
}

在上述代码中,做了几次实验,得出下列数据:

其中,总记录数是2296605,第一次测试是一下全部取出,需要占用2G左右内存,整个执行时间是4分多钟,逐步减少每次取出的记录数,当然同时要增加取出次数,当一次取出的次数在16W左右时,程序执行时间最短。
相同的代码在不同的数据规模上性能表现差别巨大,所以写代码还是要注意要处理的数据规模。

Posted in PHP.