HP性能优化利器:对象迭代生成器 yield理解

协程:

就是在单线程中使用同步编程思想来实现异步的处理流程,从而实现单线程能并发处理成百上千个请求,而且每个请求的处理过程是线性的,没有使用晦涩难懂的callback机制来衔接处理流程

yield生成器是php5.5之后出现的,yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低。

  • 生成器会对PHP应用的性能有非常大的影响
  • PHP代码运行时节省大量的内存
  • 比较适合计算大量的数据

生成器(Generator)

composer require amphp/amp       PHP应用程序的非阻塞并发框架。

网址 https://packagist.org/?query=amp  或 https://github.com/amphp/amp

<?php
#!/usr/bin/env php
require __DIR__ . '/../../vendor/autoload.php';
use Amp\Delayed;
use Amp\Loop;
use function Amp\asyncCall;
// Shows how two for loops are executed concurrently.
// Note that the first two items are printed _before_ the Loop::run()
// as they're executed immediately and do not register any timers or defers.
asyncCall(function () {
    for ($i = 0; $i < 5; $i++) {
        print "1 - " . $i . PHP_EOL;
        yield new Delayed(1000);
    }
});
asyncCall(function () {
    for ($i = 0; $i < 5; $i++) {
        print "2 - " . $i . PHP_EOL;
        yield new Delayed(400);
    }
});
print "-- before Loop::run()" . PHP_EOL;
Loop::run();
print "-- after Loop::run()" . PHP_EOL;

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值