带宽
1. Get
public function testGet()
{
$start = microtime(true);
$num = 0;
$rs = TestModel::get();
foreach ($rs as $v) {
$num++;
}
$end = microtime(true);
echo $num . PHP_EOL;
echo ($end - $start) . PHP_EOL;
$memory = memory_get_peak_usage(true) / 1024 / 1024;
echo 'memory: ' . $memory . 'MB';
}
WiFi测试
记录:42629 条
耗时:2.4276258945465 秒
内存:150.0078125 MB
手机流量热点测试
42629
21.188199996948
memory: 156.0078125MB
2. Cursor
function testCursor()
{
$start = microtime(true);
$num = 0;
foreach (TestModel::cursor() as $v) {
$num++;
}
$end = microtime(true);
echo $num . PHP_EOL;
echo ($end - $start) . PHP_EOL;
$memory = memory_get_peak_usage(true) / 1024 / 1024;
echo 'memory: ' . $memory . 'MB';
}
WiFi测试
记录:42629 条
耗时:2.2276830673218 秒
内存:13.05859375 MB
手机流量热点测试
42629
22.718268156052
memory: 17.05859375MB
3. Chunk
public function testChunk()
{
$start = microtime(true);
$num = 0;
TestModel::chunk(1000, function ($rs) use (&$num) {
foreach ($rs as $v) {
$num++;
}
});
$end = microtime(true);
echo $num . PHP_EOL;
echo ($end - $start) . PHP_EOL;
$memory = memory_get_peak_usage(true) / 1024 / 1024;
echo 'memory: ' . $memory . 'MB';
}
WiFi测试
记录:42629 条
耗时:5.1229059696198 秒
内存:2 MB
手机流量热点测试
42629
30.090832948685
memory: 2MB
4. Offset
public function testOffset()
{
$start = microtime(true);
$num = 0;
$limit = 1000;
$count = TestModel::count();
$page = ceil($count / $limit);
for ($i = 1; $i <= $page; $i++) {
$offset = ($i - 1) * $limit;
$list = TestModel::offset($offset)
->limit($limit)
->get();
foreach ($list as $v) {
$num++;
}
}
$end = microtime(true);
echo $num . PHP_EOL;
echo ($end - $start) . PHP_EOL;
$memory = memory_get_peak_usage(true) / 1024 / 1024;
echo 'memory: ' . $memory . 'MB';
}
WiFi测试
记录:42629 条
耗时:6.1690862178802 秒
内存:2 MB
手机流量热点测试
42629
30.897890090942
memory: 2MB
总结
耗时:offset(`6.16s`) > chunk(`5.12s`) > get(`2.43s`) > cursor (`2.23s`)
内存占用:get(`150MB`) > cursor(`13MB`) > offset(`2MB`) = chunk(`2MB`)
注意:用一个大表记录数达到20万的时候测试
cursor() get() 均会内存溢出
Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes)
参考结论:
在读取大量记录并遍历的使用场景中:依据 数据量 大小可以选择不同的方式
超过10万级别的数据:chunk、offset最稳健;
小于10万级别的数据:cursor效率最高;
注:这里10万级别数据差不多是300MB左右的数据;按具体情况使用;
|