Skip to content

Instantly share code, notes, and snippets.

@bobmagicii
Last active December 10, 2015 00:19
Show Gist options
  • Save bobmagicii/0321a692da43bf730db9 to your computer and use it in GitHub Desktop.
Save bobmagicii/0321a692da43bf730db9 to your computer and use it in GitHub Desktop.
<?php
/*//
this comparing two methods of writing templates. i was indecisive about which
style i should use when using datastore capable objects in templates. to decide
which way i like i decided to let the numbers speak for themselves.
so we have this datastore and to dump it into an html template takes 3 lines of
code regardless of which way i do it.
<?php $Datastore->Each(function($Item){ ?>
render html
<?php }); ?>
vs
<?php foreach($Datastore as $Item): ?>
render html
<?php endforeach; ?>
i know damn well that the loop version will be faster, but i wanted to know if
it will be faster enough that it should persuade me from using the Each method.
i was already on the fence about each because breaking out of PHP in the middle
of a function felt wrong. the result of this test will help me decide on the
preferred pattern in use here.
//*/
/*//
$ php tests/b1.php
Each: 0.73465299606323s, Loop: 0.12960004806519s
Difference: Callable is 0.60505294799805s Slower
$ php --version
PHP 7.0.0-2+deb.sury.org~trusty+1 (cli) ( NTS )
Conclusion: Yeah, we'll use the loop method instead.
//*/
class Whatever {
public $Items;
public function
__Construct() {
for($Count = 0; $Count < 10000000; $Count++)
$this->Items[] = $Count;
return;
}
public function
Each($Function) {
foreach($this->Items as $Item)
$Function($Item);
return $this;
}
}
$Whatever = new Whatever;
$First = $Second = $Start = 0;
// now we will simulate an html template. to compare the each to a simple
// loop instead. of course the straight loop will be faster, but what i need
// to know to form my opinion is, is it faster by a landslide or not. because
// if not then i will write what i think was nicer, which is the each.
?>
<?php $Start = microtime(true); $Whatever->Each(function($What){ ?>
<?php $What; ?>
<?php }); $First = (microtime(true) - $Start); ?>
<?php $Start = microtime(true); foreach($Whatever->Items as $What): ?>
<?php $What; ?>
<?php endforeach; $Second = (microtime(true) - $Start); ?>
<?php
echo "Each: {$First}s, Loop: {$Second}s", PHP_EOL;
echo "Difference: Callable is ", ($First - $Second), "s Slower", PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment