mathiasbynens / utf8.js

A robust JavaScript implementation of a UTF-8 encoder/decoder, as defined by the Encoding Standard.
https://git.io/utf8js
MIT License
556 stars 115 forks source link

Optimization: Check whether encoding/decoding is needed #31

Open mudcube opened 7 years ago

mudcube commented 7 years ago

Would it make sense to check whether encoding/decoding is needed?

if (/^[\u0000-\u007F]*$/i.test(str)) {
    return str
} else {
    return encode(str) // or decode(str)
}

Use case—I'm using UTF8.js to encode SVGs into dataURLs, and for larger SVGs it can take a little bit of time to encode them (not a huge amount, maybe 100ms per MB). Most of the time the SVGs do not actually need encoding as they're entirely ASCII, this RegExp check is fairly quick, so saves a bit of time overall.