esprima-dotnet icon indicating copy to clipboard operation
esprima-dotnet copied to clipboard

Change Token to be a struct

Open lahma opened this issue 2 years ago • 2 comments

Work started here, let's see if it flies with performance benefits: https://github.com/sebastienros/esprima-dotnet/pull/236

lahma avatar Jun 08 '22 17:06 lahma

Now that JsxToken inherits from Token which would have been struct things are not as straightforward.

lahma avatar Jul 21 '22 19:07 lahma

Though inheritance is not possible, we still have composition as an option:

public struct Token
{
    public TokenType Type;
    // ...

    public object? ExtensionData;
}`

Of course, this only solves the base parser's problem, JsxParser can't really avoid allocations. However, JsxToken needs an extra field only, which has two possible values (see JsxTokenType). These can be pre-cached in static readonly fields:

private static readonly object JsxIdentifierTokenType = JsxTokenType.JsxIdentifier;
private static readonly object JsxTextTokenType = JsxTokenType.JsxText;

And then

var token = new JsxToken()
{
    Type = JsxTokenType.JsxText,
    Value = text,
    // ...
};

becomes:

var token = new Token()
{
    Type = TokenType.Extension,
    ExtensionData = JsxTextTokenType 
    Value = text,
    // ...
};

adams85 avatar Jul 21 '22 21:07 adams85