mathiasbynens / jsesc

Given some data, jsesc returns the shortest possible stringified & ASCII-safe representation of that data.
https://mths.be/jsesc
MIT License
716 stars 53 forks source link

Performance for escaping strings #16

Open joliss opened 10 years ago

joliss commented 10 years ago

For escaping strings, jsesc is about 10x slower than js-string-escape:

$ time node -e "var escape=require('jsesc'); for (var i = 0; i < 1000000; i++) { escape('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') }"

real    0m2.490s
user    0m2.485s
sys 0m0.024s
$ time node -e "var escape=require('js-string-escape'); for (var i = 0; i < 1000000; i++) { escape('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') }"

real    0m0.217s
user    0m0.170s
sys 0m0.051s

This turns out to be relevant in practice: Building my sample JavaScript app takes twice as long when I use jsesc.

mathiasbynens commented 10 years ago

Any ideas on how to improve jsesc’s performance?

I guess this is the cost we pay for the additional functionality compared to js-string-escape, no?

joliss commented 10 years ago

I'd be surprised if there's anything fundamentally stopping us from optimizing jsesc. If I wanted to optimize jsesc, I'd probably try different approaches to the inner escape loop.

joliss commented 10 years ago

I remember trying a bunch of implementations for js-string-escape, and replace surprisingly turned out to be quite fast, despite the closure function.