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

#!/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;

你可能感兴趣的:(php)