From b98ede743a3e6cb1a12b306092629447797d5afa Mon Sep 17 00:00:00 2001 From: Tyson Andre Date: Wed, 20 Sep 2017 09:00:13 -0700 Subject: [PATCH] Speed up token value to name lookup Grammar test suite sped up from 1.2 seconds to 1.1 seconds. This went from O(n) (loop over 183 constants) to O(1) (hash lookup) --- src/Token.php | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/Token.php b/src/Token.php index d40770b5..12abaee4 100644 --- a/src/Token.php +++ b/src/Token.php @@ -59,15 +59,25 @@ public function getEndPosition() { return $this->fullStart + $this->length; } - public static function getTokenKindNameFromValue($kindName) { - $constants = (new \ReflectionClass("Microsoft\\PhpParser\\TokenKind"))->getConstants(); - foreach ($constants as $name => $val) { - if ($val == $kindName) { - $kindName = $name; - break; - } + /** + * @return string[] - A hash map of the format [int $tokenKind => string $tokenName] + */ + private static function getTokenKindNameFromValueMap() { + static $mapToKindName; + if ($mapToKindName === null) { + $constants = (new \ReflectionClass("Microsoft\\PhpParser\\TokenKind"))->getConstants(); + $mapToKindName = \array_flip($constants); } - return $kindName; + return $mapToKindName; + } + + /** + * @param int $kind + * @return string (Or int, if the kind name for $kind wasn't found) + */ + public static function getTokenKindNameFromValue($kind) { + $mapToKindName = self::getTokenKindNameFromValueMap(); + return $mapToKindName[$kind] ?? $kind; } public function jsonSerialize() {