Skip to content

tadashibashi/js-stringbuilder

Repository files navigation

logo

A dynamic string class for optimal text manipulation

  • Array-like flexibility to control strings

  • Significantly faster than JS string concatenation and split Array handling

  • Automatic memory management with ability to allocate or shrink space as needed

  • Convenient API

  • Best Use Cases

    • handling large streams of text
    • altering large files

Main repository hosted on GitHub.

Tools

TypeScript JavaScript Jest Typedoc

Interest in StringBuilder

JavaScript strings are immutable primitives that create garbage for every unique sequence generated via concatenation, slicing, etc.

StringBuilder attempts to provide an efficient way to dynamically build JavaScript strings, friendly toward the garbage collector.

Installation

Build JavaScript file

with yarn:

yarn install
yarn build

with npm:

npm i
npm run build

Example Usage

Create a StringBuilder string

// Set initial character length if you know its size ahead of time,
const stringBuilder = new StringBuilder(1000000);

// or later via `reserve`.
stringBuilder.reserve(1000000);

// Efficient for lots of appending,
for (let i = 0; i < 1000000; ++i)
    stringBuilder.append((i % 10).toString());

// then retrieve the final value.
let str = stringBuilder.str(); // "01234567890123..."

Insertion and deletion via splice

const stringBuilder = new StringBuilder("01234");

stringBuilder.splice(0, 1, "abc");

let str = stringBuilder.str(); // "0abc234"

Find & replace

const stringBuilder = new StringBuilder("Hello world!");

// mutates internal string
stringBuilder.replace(/world/, "StringBuilder");

console.log(stringBuilder.str()); // "Hello StringBuilder!"

Documentation

Hosted here: https://code.aaronishibashi.com/js-stringbuilder

Performance Comparison

StringBuilder String Array<string>
500,000 char appends 5.26ms 22.55ms 17.65ms
500,000 mid-insertions 2,465.29ms 20,761.87ms 9,658.66ms
500,000 char prepends 7.38ms 25.65ms 19,334.63ms
StringBuilder String Array<string>
1 million char appends 6.90ms 51.77ms 30.11ms
1 million mid-insertions 9,735.18ms 72,645.41ms 88,937.65ms
1 million char prepends 38.18ms 52.75ms 80,454.23ms

These metrics were tested in Node v20.3.1 on an ARM MacOS 13.

To run the tests on your own machine use: yarn test:perf or npm run test:perf

Please let me know if there is any performance issue on your system :-)

Roadmap

  • search
  • incorporate regexp
  • documentation
  • implement replaceAll
  • extensive testing

Releases

No releases published

Packages

No packages published