Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
__callStatic: cache created Enum instances
Instead of creating a new one each time, cache them.

This only matters if you're creating thousands of these objects.

I've used a small test script:

    <?
    require './vendor/autoload.php';

    class Fast extends MyCLabs\Enum\Enum {
       protected const VALUE_ONE = "one";
       protected const VALUE_TWO = "two";
    }

    $t = microtime(true);
    for ($i = 0; $i < 1000; $i++) {
       Fast::VALUE_ONE();
    }
    $secondsPerOp = (microtime(true) - $t) / 1000;
    var_dump("Microseconds per op: " . $secondsPerOp * 1000000);

Before this change, we were getting about 4us per operation,
after this, we get about 1us per op, a 4X speedup!!

Note: This only matters if you end up constrcuting thousands of these
objects. We end up using this library extensively and thus end up
incurring more than ten milliseconds per request just for Enum
construction.
  • Loading branch information
danielbeardsley committed Oct 28, 2020
commit 82ec4acb757679ddc164f7b27b1fc527b079cde3
22 changes: 16 additions & 6 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ abstract class Enum implements \JsonSerializable
*/
protected static $cache = [];

/**
* Cache of instances of the Enum class
*
* @var array
* @psalm-var array<class-string, array<string, static>>
*/
protected static $instances = [];

/**
* Creates a new value of some type
*
Expand Down Expand Up @@ -211,17 +219,19 @@ public static function search($value)
* @param array $arguments
*
* @return static
* @psalm-pure
* @throws \BadMethodCallException
*/
public static function __callStatic($name, $arguments)
{
$array = static::toArray();
if (isset($array[$name]) || \array_key_exists($name, $array)) {
return new static($array[$name]);
$class = static::class;
if (!isset(self::$instances[$class][$name])) {
$array = static::toArray();
if (!isset($array[$name]) && !\array_key_exists($name, $array)) {
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . static::class);
}
return self::$instances[$class][$name] = new static($array[$name]);
}

throw new \BadMethodCallException("No static method or enum constant '$name' in class " . static::class);
return self::$instances[$class][$name];
}

/**
Expand Down