Created
January 5, 2017 01:55
-
-
Save p810/d2c1dc78c40a8c6f25c3204c7f9f50a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Foo implements Iterator | |
{ | |
private $position = 0; | |
protected $data; | |
function __construct() { | |
$this->data = range(1, 100); | |
} | |
public function rewind() { | |
$this->position = 0; | |
} | |
public function current() { | |
return $this->data[$this->position]; | |
} | |
public function key() { | |
return $this->position; | |
} | |
public function next() { | |
++$this->position; | |
} | |
public function valid() { | |
return isset($this->data[$this->position]); | |
} | |
} | |
class Bar | |
{ | |
public function iterate() { | |
foreach (range(1, 100) as $item) { | |
yield $item; | |
} | |
} | |
} | |
$foo = new Foo; | |
$bar = new Bar; | |
$fooScore = 0; | |
$barScore = 0; | |
for ($i = 0; $i < 100000; $i++) { | |
if ($i > 0) { | |
print PHP_EOL; | |
} | |
print PHP_EOL . '+-----------------------------------------------------+' . PHP_EOL; | |
(function () use ($foo, $bar, &$fooScore, &$barScore) { | |
$start = microtime(true); | |
foreach ($foo as $item) { | |
continue; | |
} | |
$end = microtime(true); | |
$fooDuration = $end - $start; | |
print sprintf('Foo<Iterator>: %f', $fooDuration) . PHP_EOL; | |
$start = microtime(true); | |
foreach ($bar->iterate() as $item) { | |
continue; | |
} | |
$end = microtime(true); | |
$barDuration = $end - $start; | |
print sprintf('Bar::iterate(): %f', $barDuration); | |
$result = $fooDuration <=> $barDuration; | |
switch ($result) { | |
case -1: | |
$fooScore++; | |
break; | |
case 0: | |
$fooScore--; | |
$barScore--; | |
break; | |
case 1: | |
$barScore++; | |
break; | |
} | |
})(); | |
print PHP_EOL . '+-----------------------------------------------------+' . PHP_EOL; | |
} | |
print sprintf('Foo<Iterator>: %d', $fooScore) . PHP_EOL; | |
print sprintf('Bar::iterate(): %d', $barScore); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment