Max Heiber
Max Heiber

Reputation: 15502

How does identifier interning work in the TypeScript compiler?

in the TypeScript compiler, src/compiler/parser.ts contains the following, where identifiers is a Map of strings to strings:

function internIdentifier(text: string): string {
    let identifier = identifiers.get(text);
    if (identifier === undefined) {
       identifiers.set(text, identifier = text);
    }
    return identifier;
}

This has the same behavior as the identify function for strings:

const id = (text: string) => text

I assume it's there for performance. How could this improve performance? I'm asking because:

Upvotes: 1

Views: 295

Answers (1)

JB Nizet
JB Nizet

Reputation: 691785

It saves on memory. Take the following example:

const s1 = readFromFile();
const s2 = readFromFile();
const s3 = readFromFile();

How many different string objects do you have in memory? 3, but all contain the same characters.

Now take the following:

const s1 = internIdentifier(readFromFile());
const s2 = internIdentifier(readFromFile());
const s3 = internIdentifier(readFromFile());

How many different string objects do you have in memory? Just 1. All three variables refer to the same string object.

Upvotes: 1

Related Questions