Langweiliges Zeug. Was sonst.
stringToBytes JavaScript Performance

Searching for a simple function to convert javascript strings to byte arrays, I stumbled over this stackoverflow answer.

While it’s implementation is correct, it has a significant performance problem. For large strings, the internal byte array is recreated too often. It’s somewhat similar to using the += operator on strings in java instead of using a StringBuilder. A faster function is below.
function stringToBytesFaster ( str ) { 
    var ch, st, re = [], j=0;
    for (var i = 0; i < str.length; i++ ) { 
        ch = str.charCodeAt(i);
        if(ch < 127)
        {
            re[j++] = ch & 0xFF;
        }
        else
        {
            st = [];    // clear stack
            do {
                st.push( ch & 0xFF );  // push byte to stack
                ch = ch >> 8;          // shift value down by 1 byte
            }
            while ( ch );
            // add stack contents to result
            // done because chars have "wrong" endianness
            st = st.reverse();
            for(var k=0;k<st.length; ++k)
                re[j++] = st[k];
        }
    }   
    // return an array of bytes
    return re; 
}
To round up things, you can start a performance test here: clickme
Example output on Firefox 8, core2duo and strlength = 10000:
Old: 2021ms
New: 4ms

Speedup factor:505.25
  1. langweiligeszeug posted this