4 ms·
That code takes a terrible detour. To do a simple reduction, you build a STRING, hand it over to the parser, which creates an expression, which is converted to
by wladimir 14y ago
That code takes a terrible detour. To do a simple reduction, you build a STRING, hand it over to the parser, which creates an expression, which is converted to bytecode and then it can be interpreted/JIT-ed.
I can't imagine it actually being faster than normal array functions, and if it's the case it yet again proved what an abysmal language JS is :-)
But seriously, don't use eval this way. The array may not seem to contain user input on first glance, but it's very fragile: a small bug, a change to the code (for example, by another programmer, or by you when you're not paying attention) can easily cause it to be.
You're never "smart enough" to go around basic security guidelines to gain some (questionable) speed.
I think it's a good question by the grandparent what eval is good for. Arguably it allows for some powerful paradigms such as generating code at run time, but similar things can be done with function closures and eval is just too often abused for parsing (wasn't there window.JSON.parse for that?)
- kevincennis 14y agoAll I'm saying is that if I'm putting together a quick demo or proof of concept or reduced test case, I'm always going to favor "easy" over "secure". And sometimes using eval is easier. By the way, the performance of evaling an array that way is abysmal: http://jsperf.com/array-summing-loop-vs-eval http://jsperf.com/array-summing-loop-vs-eval