Text into words

Benchmark created on


Setup

const DELIMITER = " ";

const myString = "   Hello    this is my    World   ";

function splitIntoWords(string) {
    const words = [];

    let buffer = "";

    for (let i = 0; i < string.length; i++) {
        const char = string[i];

        if (char !== DELIMITER) {
            while (i < string.length && string[i] !== DELIMITER) {
                buffer += string[i];
                i++;
            }

            words.push(buffer);
            buffer = "";
        }
    }

    return words;
}

function splitIntoWords2(string) {
    const words = [];

    let buffer = "";

    for (let i = 0; i < string.length; i++) {
        const char = string[i];

        if (char !== DELIMITER) {
            buffer += char;
        } else if (buffer.length > 0) {
            words.push(buffer);
            buffer = "";
        }
    }

    return words;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Trim + Replace + Split
myString.trim().replace(/\s+/g, DELIMITER).split(DELIMITER)
ready
splitIntoWords
splitIntoWords(myString)
ready
splitIntoWords2
splitIntoWords2(myString)
ready
Trim + Split + Filter
myString.trim().split(DELIMITER).filter(s => !!s.trim())
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.