Performance optimizations for strings

When working with strings, there are a number of easy performance optimizations that can produce noticeable performance improvements.

Concatenation in a loop

Avoid repeated string concatenation in loops - use .join() with arrays instead.

In each iteration of the loop, a new memory location needs to be allocated for the resulting string. Consider the two implementations below of a function to generate a random identifier by joining random characters - the join implementation is around twice as fast as the version with a loop.

Loading TypeScript...

Emojis

Be cautious with .length and indexing when working with emojis or multi-code-unit characters.

TextEncoder

Use TextEncoder/TextDecoder for working with raw byte encodings (e.g. UTF-8).

Was this page helpful?