Based on the following benchmarks, this appears to be the fastest choice that works on all platforms:
- In Node.js:
Buffer.byteLength(string)
. - Otherwise:
new TextEncoder().encode(string).length
on big strings.String.charCodeAt()
(as described here) on small strings. At what point a string is "big" depends on your machine (for me, it's roughly 300 characters).
I have created the following library that implements the above:
import stringByteLength from 'string-byte-length'stringByteLength('test') // 4stringByteLength('') // 1stringByteLength('\0') // 1stringByteLength('±') // 2stringByteLength('★') // 3stringByteLength('🦄') // 4