3 ms·
We probably should be cautious reading anything about JS optimization that's 12 years old. It might have been true at the time, but now with the highly-optimize
by lucasmullens 6y ago
We probably should be cautious reading anything about JS optimization that's 12 years old. It might have been true at the time, but now with the highly-optimized V8 engine, and a set of native methods that didn't exist back then, there's a pretty good chance there's another way to do this that's even faster.
- throwanem 6y agoIt can certainly be done at least as fast and much more legibly. Probably not in 2008 - which predates even ES5 by a year! - but these days, most certainly.
- Stratoscope 6y agoThat is very true. I wrote a polygon drawing library the same year of this blog post, and I pulled out all the stops to make it as fast as possible on the browsers of the day - including IE6! Now of course many of the tricks I used backfire in modern engines, and simple straightforward code is faster. Perhaps a more important point is that this particular problem does not need to be optimized, and shouldn't be optimized! It should use the simplest and most understandable code possible. Even in the era of slow browsers from 10-15 years ago. It's a query string, not a million-row database.
- deleted 6y ago[deleted]
- rezonant 6y agoTruer words! I did a quick microbench of a few implementations of this and found that Resig's implementation is far from the best performance possible. PSA: Microbenchmarks are not indicative of real world performance Find the code here: https://gist.github.com/rezonant/639c67db5bd6503e8f022291b918bb62 https://gist.github.com/rezonant/639c67db5bd6503e8f022291b91... Results on my system (Core i7 7700, Node.js 10.15.3, Windows 10 2004): ---- Comparing 7 implementations, 1000000 repetitions each short input: resig: 2920ms resigModernized: 2369ms fullyFunctional: 2817ms functionalHybrid: 2352ms mapReduce: 5002ms splitmap: 1490ms compressURL: 6064ms long input, few keys: resig: 28664ms resigModernized: 23087ms fullyFunctional: 17509ms functionalHybrid: 18431ms mapReduce: 46959ms splitmap: 14791ms compressURL: 24485ms long input, many keys: resig: 17468ms resigModernized: 15049ms fullyFunctional: 15781ms functionalHybrid: 13768ms mapReduce: 30352ms splitmap: 12959ms compressURL: 34180ms ---- The winner (according to this crude benchmark) is this implementation: function splitmap(data){ let q = new Map(); for (let [key, value] of data.split(/&/g).map(x => x.split(/=/))) { q.set(key, `${q.has(key) ? q.get(key) + ',' : ''}${value}`); } let ret = ""; for (let [ key, value ] of q) ret = `${ret ? ret + '&' : ''}${key}=${value}`; return ret; } ...but I'm sure folks can come up with something faster EDIT: The splitmap() implementation will fail on key=value=foo, cutting off the extra "=foo", though if you are expecting valid URL-encoded params then this might be an acceptable limitation.