php cursor scroll,Laravel Get() Cursor() Chunk() Offset()对比

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左右的数据;按具体情况使用;

参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值