Skip to content

Commit b98ede7

Browse files
TysonAndreTysonAndre-tmg
authored andcommitted
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)
1 parent fc98829 commit b98ede7

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/Token.php

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,25 @@ public function getEndPosition() {
5959
return $this->fullStart + $this->length;
6060
}
6161

62-
public static function getTokenKindNameFromValue($kindName) {
63-
$constants = (new \ReflectionClass("Microsoft\\PhpParser\\TokenKind"))->getConstants();
64-
foreach ($constants as $name => $val) {
65-
if ($val == $kindName) {
66-
$kindName = $name;
67-
break;
68-
}
62+
/**
63+
* @return string[] - A hash map of the format [int $tokenKind => string $tokenName]
64+
*/
65+
private static function getTokenKindNameFromValueMap() {
66+
static $mapToKindName;
67+
if ($mapToKindName === null) {
68+
$constants = (new \ReflectionClass("Microsoft\\PhpParser\\TokenKind"))->getConstants();
69+
$mapToKindName = \array_flip($constants);
6970
}
70-
return $kindName;
71+
return $mapToKindName;
72+
}
73+
74+
/**
75+
* @param int $kind
76+
* @return string (Or int, if the kind name for $kind wasn't found)
77+
*/
78+
public static function getTokenKindNameFromValue($kind) {
79+
$mapToKindName = self::getTokenKindNameFromValueMap();
80+
return $mapToKindName[$kind] ?? $kind;
7181
}
7282

7383
public function jsonSerialize() {

0 commit comments

Comments
 (0)