Skip to content

Instantly share code, notes, and snippets.

@haampie
Created July 25, 2016 21:28
Show Gist options
  • Save haampie/f35d1623a07860c0440f4079a29ea316 to your computer and use it in GitHub Desktop.
Save haampie/f35d1623a07860c0440f4079a29ea316 to your computer and use it in GitHub Desktop.
Hydration methods
<?php
$iterations = 1000000;
class Example
{
private $a;
private $b;
private $c;
private $d;
private $e;
private $f;
}
class NewHydrator extends Example
{
private $a = null;
private $b = null;
private $c = null;
private $d = null;
private $e = null;
private $f = null;
function __construct()
{
$this->touchA = function ($value) {
$this->a = $value;
};
$this->touchB = function ($value) {
$this->b = $value;
};
$this->touchC = function ($value) {
$this->c = $value;
};
$this->touchD = function ($value) {
$this->d = $value;
};
$this->touchE = function ($value) {
$this->e = $value;
};
$this->touchF = function ($value) {
$this->f = $value;
};
}
function hydrate(array $data, $object)
{
$this->touchA->call($object, $data['a']);
$this->touchB->call($object, $data['b']);
$this->touchC->call($object, $data['c']);
$this->touchD->call($object, $data['d']);
$this->touchE->call($object, $data['e']);
$this->touchF->call($object, $data['f']);
return $object;
}
}
class OldHydrator extends Example
{
private $a = null;
private $b = null;
private $c = null;
private $d = null;
private $e = null;
private $f = null;
function __construct()
{
$this->touchA = \Closure::bind(function ($object, $value) {
$object->a = $value;
}, null, 'Example');
$this->touchB = \Closure::bind(function ($object, $value) {
$object->b = $value;
}, null, 'Example');
$this->touchC = \Closure::bind(function ($object, $value) {
$object->c = $value;
}, null, 'Example');
$this->touchD = \Closure::bind(function ($object, $value) {
$object->d = $value;
}, null, 'Example');
$this->touchE = \Closure::bind(function ($object, $value) {
$object->e = $value;
}, null, 'Example');
$this->touchF = \Closure::bind(function ($object, $value) {
$object->f = $value;
}, null, 'Example');
}
function hydrate(array $data, $object)
{
$this->touchA->__invoke($object, $data['a']);
$this->touchB->__invoke($object, $data['b']);
$this->touchC->__invoke($object, $data['c']);
$this->touchD->__invoke($object, $data['d']);
$this->touchE->__invoke($object, $data['e']);
$this->touchF->__invoke($object, $data['f']);
return $object;
}
}
echo "Old implementation\n";
$start = microtime(true);
for ($i=0; $i != $iterations; $i++) {
$hydrator = new OldHydrator;
}
var_dump(microtime(true) - $start);
echo "New implementation\n";
$start = microtime(true);
for ($i=0; $i != $iterations; $i++) {
$hydrator = new NewHydrator;
}
var_dump(microtime(true) - $start);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment