From ad96a584d5eb0a6c29e2a2506e582673ad83bfb7 Mon Sep 17 00:00:00 2001 From: Daniel Lowrey Date: Tue, 16 Jun 2015 12:08:24 -0400 Subject: [PATCH] Check coroutine nesting level before incurring "next tick" overhead --- lib/functions.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/functions.php b/lib/functions.php index e3eb890..57fb21a 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -550,6 +550,7 @@ function resolve(\Generator $generator, Reactor $reactor = null) { $cs->generator = $generator; $cs->returnValue = null; $cs->currentPromise = null; + $cs->nestingLevel = 0; __coroutineAdvance($cs); @@ -573,8 +574,14 @@ function __coroutineAdvance($cs) { $cs->returnValue = $yielded; __coroutineSend(null, null, $cs); } elseif ($yielded instanceof Promise) { - $cs->currentPromise = $yielded; - $cs->reactor->immediately("Amp\__coroutineNextTick", ["cb_data" => $cs]); + if ($cs->nestingLevel < 3) { + $cs->nestingLevel++; + $yielded->when("Amp\__coroutineSend", $cs); + $cs->nestingLevel--; + } else { + $cs->currentPromise = $yielded; + $cs->reactor->immediately("Amp\__coroutineNextTick", ["cb_data" => $cs]); + } } else { $error = new \DomainException(makeGeneratorError($cs->generator, sprintf( 'Unexpected yield (Promise|null|"return" expected); %s yielded at key %s',