Skip to content

Instantly share code, notes, and snippets.

@orolyn
Last active June 6, 2016 12:28
Show Gist options
  • Save orolyn/ff70f512efee36d402d1fc4fbc8f0521 to your computer and use it in GitHub Desktop.
Save orolyn/ff70f512efee36d402d1fc4fbc8f0521 to your computer and use it in GitHub Desktop.
Emulated Overloading
<?php
/*
* DISCLAIMER: This is a benchmark, not a use case. Please forgive the rudimentary example below.
*
* The following demonstrates a relatively common implementation of overload emulation.
*
* The benchmark measures the overhead in counting the anonymous arguments
* and delegating the the respective function.
*
* With an input of 10000000 iterations, this PC gives the following results:
*
* DIFFERENT FUNCTIONS: 2
* OVERLOADED: 13
*
* With proper overloading, the "add_2" and "add_3" function would be simply:
*
* function add($a, $b) {}
* function add($a, $b, $c) {}
*
* With a performance similar to, but slightly degraded from 2 seconds, depending on the number of
* instructions saved internally.
*/
function add_2($a, $b)
{
return $a + $b;
}
function add_3($a, $b, $c)
{
return $a + $b + $c;
}
function overloaded(... $args)
{
$count = count($args);
if (2 === $count) {
return add_2($args[0], $args[1]);
} elseif (3 === $count) {
return add_3($args[0], $args[1], $args[2]);
}
}
$count = (int) $argv[1];
// DIFFERENT FUNCTIONS
$time = time();
for ($i = 0; $i < $count; $i++) {
add_2($i, 1);
add_3($i, 1, 2);
}
echo 'DIFFERENT FUNCTIONS: '. (time() - $time) . PHP_EOL;
// OVERLOADED
$time = time();
for ($i = 0; $i < $count; $i++) {
overloaded($i, 1);
overloaded($i, 1, 2);
}
echo 'OVERLOADED: '. (time() - $time) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment