Eval is evil, part two

As
I promised, more information on why eval is evil.  (We once considered having
T-shirts printed up that said “Eval is evil!” on one side and “Script happens!” on
the other, but the PM’s never managed to tear themselves away from their web browsing
long enough to order them.)

 

 

/>Incidentally, a buddy
of mine who is one of those senior web developer kinda guys back in

Waterloo
sent me an email yesterday saying “Hello, my name is Robert and I am an evalaholic”.
People, it wasn’t my intention to
start a twelve step program, but hey, whatever works!

 

As
discussed
the other day
, eval on
the client is evil because it leads to sloppy, hard-to-debug-and-maintain programs
that consume huge amounts of memory and run unnecessarily slowly even when performing
simple tasks.  But like I said in my performance
rant
, if it’s good
enough
, then hey, it’s good enough.  Maybe
you don’t need to write maintainable,
efficient code.  Seriously! Script is
often used to write programs that are used a couple of times and then thrown away,
so who cares if they’re slow and inelegant?

 

But eval on
the server is an entirely different beast.  First
off, server scenarios are generally a lot more performance sensitive than client scenarios.  On
a client, once your code runs faster than a human being can notice the lag, there’s
usually not much point in making it faster.  But  as
I mentioned earlier
, ASP goes to a lot of work to ensure that for a given page,
the compiler only runs once. An eval defeats
this optimization by making the compiler run every time the page runs! On a server,
going from 25 ms to 40 ms to serve a page means going from 40 pages a second to 25
pages a second, and that can be expensive in real dollar terms.

 

But
that’s not the most important reason to eschew eval on
the server.  Any use of eval (or
its VBScript cousins Eval, Execute and ExecuteGlobal)
is a potentially enormous security hole. 

 

<%

var
Processor_ProductList;

var
Software_ProductList;

var
HardDisk_ProductList;

//

CategoryName
= Request.QueryString(“category”);

ProductList
= eval(CategoryName & “_ProductList”);

//

 

What’s
wrong with this picture?  The
server assumes that the client is not hostile.
  Is
that a warranted assumption?  Probably
not!  You know nothing about the client
that sent the request.  Maybe your client
page only sends strings like “Processor” and “HardDisk” to the server, but anyone
can write their own web page that sends

 

((new
ActiveXObject(‘Scripting.FileSystemObject’)).DeleteFile(‘C:*.*’,true)); Processor

 

which
will cause eval to
evaluate

 

((new
ActiveXObject(‘Scripting.FileSystemObject’)).DeleteFile(‘C:*.*’,true)); Processor_ProductList

 

Obviously
that’s a pretty unsophisticated attack.  The
attacker can put any
code in there that they want
, and it will run in the context of the server process.  Hopefully
the server process is not a highly privileged one, but still, there’s vast potential
for massive harm here just by screwing up the logic on your server.

 

Never
trust the input to a server, and try to never use 
eval on
a server.  
Eval injection
makes SQL injection look tame!

 

To
try and mitigate these sorts of problems, JScript .NET has some restrictions on its
implementation of eval,
but that’s a topic for another entry.

 

Tags ASP JScript Performance Scripting Security

Comments (6)

You must be logged in to post a comment.

  1. CliffGreat information, but how about some advice on what to use as an alternative?  The point to Eval/Execute is to provide the ability to execute code that you wont know you need until the last minute.  I can see why Eval might be bad, but how would one go about it otherwise?Log in to Reply
  2. Answers are the difference between being a thermometer & a thermostat.  Thermometers just let you know something is wrong.  A thermostat sees the problem & then takes action to actually do something to improve the situation.
  3. April 13, 2006 at 12:29 pm
  4. Eric LippertHow would one go about WHAT otherwise?  To answer the question, I’d have to know what eval/execute was being used for in the first place!Log in to Reply
  5. That said, _most_ uses of eval that I’ve seen could be rewritten to use a lookup table, and the resulting code would be smaller, faster, easier to maintain, and have fewer security holes.
  6. April 13, 2006 at 12:55 pm
  7. EnigmaticWe are using XAML to write validation rules which are evaluated on the fly using Eval. So how would you go about evaluating at runtime a condition whose values may change depending on the input of the user?
  8. Log in to Reply
  9. March 15, 2007 at 6:37 pm
  10. Why Won’t eval() Eval My JSON? (Or: JSON Object !== Object Literal) « The Curious SchemerPingBack from http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
  11. Log in to Reply
  12. March 28, 2007 at 2:14 pm
  13. Calling a sub | keyongtechPingBack from http://www.keyongtech.com/1169946-calling-a-sub
  14. Log in to Reply
  15. January 21, 2009 at 11:50 pm
  16. MarlinIn answer to Eric’s question, this worked for me in ASP classic, JScript:I found it at JSON .org and I saved it as json-sans-eval.asp and edited it so that it started with <% and ended with %><!– #include file=”json_sans_eval.asp” –>Worked great.
  17. Then instead of eval(X) is used jsonParse(X).
  18. Then in my code where I was using eval I put this at towards the top (outside of the <% %>
  19. code.google.com/…/json-sans-eval
  20. March 22, 2012 at 3:42 pm

A parable

Once upon a time I was in high school. Ah, the halcyon days of my youth. One day I was sitting in class, minding my own business when the teacher said: “Does anyone have a thin metal ruler?”

No answer. Apparently no one had a thin metal ruler.

“No? How about a nail file?”

No answer. Now, I cannot imagine that of all the girls in the class, not one of them had a nail file. But I can well imagine that none of them wanted to share it with a teacher.

“No? Hmm.”

So I piped up: “What do you need a nail file for?”

“I have this big staple in this document that I need to remove.”

Upon which point one of my classmates mentioned that he had a staple remover. Problem solved.

Over and over again I find that script customers (both internal consumers here at Microsoft and third-party developers) frequently ask questions like my teacher. That is, they have a preconceived notion of how the problem is going to be solved, and then ask the necessary questions to implement their preconceived solution. And in many cases this is a pretty good technique! Had someone actually brought a thin metal ruler to class, the problem would have been solved. But by choosing a question that emphasizes the solution over the problem, the questioner loses all ability to leverage the full knowledge of the questionees.

When someone asks me a question about the script technologies I almost always turn right around and ask them why they want to know. I might be able to point them at some tool that better solves their problem. And I might also learn something about what problems people are trying to solve with my tools.

Joel Spolsky once said that people don’t want drills, they want holes. As a drill provider, I’m fascinated to learn what kinds of holes people want to put in what kinds of materials, so to speak. Sometimes people think they want a drill when in fact they want a rotary cutter.


Commentary from 2019:

First off, I misattributed that quotation. “People don’t want to buy a quarter-inch drill, they want a quarter-inch hole.” is a quote from the economist Theodore Levitt. At the time I wrote this, I was sure that I had read about this idea in a Joel On Software article, but if I did, I cannot find it now. Apologies for the error.

Second, I did not know at the time that we have a name for this pattern of “have a problem, get a crazy idea about a solution, ask baffling questions about the crazy idea, rather than stating the problem directly” that we see so often on StackOverflow. It is an “XY problem“, which strikes me as a terrible name.

Third, I am reminded of a story about the time I was helping Morton Twillingate put a roof on his shed. “Hand me the screw driver there b’y,” he said so I handed him a Philips head screwdriver. “Sweet t’underin’ Jaysus b’y, give me the screw driver!” he said, pointing at the hammer in my other hand, “If I’d wanted the screw remover I’d have said so!”

 

Eval is evil, part one

The eval method
— which takes a string containing JScript code, compiles it and runs it — is probably
the most powerful and most misused method in JScript. There are a few scenarios in
which eval is
invaluable.  For example, when you are
building up complex mathematical expressions based on user input, or when you are
serializing object state to a string so that it can be stored or transmitted, and
reconstituted later.

 

However,
these worthy scenarios make up a tiny percentage of the actual usage of eval.  In
the majority of cases, eval is
used like a sledgehammer swatting a fly — it gets the job done, but with too much
power.  It’s slow, it’s unwieldy, and
tends to magnify the damage when you make a mistake.  Please
spread the word far and wide: if you are considering
using 
eval then
there is probably a better way. 
 Think
hard before you use eval.

 

Let
me give you an example of a typical usage.

 

<span
id=”myspan1″></span>

<span
id=”myspan2″></span>

<span
id=”myspan3″></span>

function
setspan(num, text)

{

eval(“myspan”
+ num + “.innerText = ‘” + text + “‘”);

}

 

Somehow
the program is getting its hands on a number, and it wants to map that to a particular
span.  What’s wrong with this picture?

 

Well,
pretty much everything.  This
is a horrid way to implement these simple semantics.
  First
off, what if the text contains an apostrophe?  Then
we’ll generate

 

myspan1.innerText
= ‘it ain’t what you do, it’s the way thacha do it’;

Which
isn’t legal JScript.  Similarly, what
if it contains stuff interpretable as escape sequences?  OK,
let’s fix that up.

 

eval(“myspan”
+ num).innerText = text;

If
you have to use 
evaleval as
little of the expression as possible, and only do it once.  
I’ve
seen code like this in real live web sites:

 

if (eval(foo)
!= null && eval(foo).blah == 123)

eval(foo).baz
= “hello”;

 

Yikes!  That
calls the compiler three times to compile up the same code!  People, eval starts
a compiler
.  Before
you use it, ask yourself whether there is a better way to solve this problem than
starting up a compiler!

 

Anyway,
our modified solution is much better but still awful.  What
if num is
out of range?  What if it isn’t even a
number?  We could put in checks, but why
bother?  We need to take a step back here
and ask what problem we are trying to solve.

 

We
have a number.  We would like to map that
number onto an object.  How would you
solve this problem if you didn’t have eval?  This
is not a difficult programming problem!  Obviously
an array is a far better solution:

 

var spans
= new Array(null, myspan1, myspan2, myspan3);

function
setspan(num, text)

{

if
(spans[num] != null)

spans[num].innertext
= text;

}

 

And
since JScript has string-indexed associative arrays, this generalizes to far more
than just numeric scenarios.  Build
any map you want.  JScript even provides
a convenient syntax for maps!

 

var spans
= { 1 : mySpan1, 2 : mySpan2, 12 : mySpan12 };

 

Let’s
compare these two solutions on a number of axes:

 

Debugability:
what is easier to debug, a program that dynamically generates new code at runtime,
or a program with a static body of code?  What
is easier to debug, a program that uses arrays as arrays, or a program that every
time it needs to map a number to an object it compiles up a small new program?

 

Maintainability:
What’s easier to maintain, a table or a program that dynamically spits new code?

 

Speed:
which do you think is faster, a program that dereferences an array, or a program that
starts a compiler?

 

Memory:
which uses more memory, a program that dereferences an array, or a program that starts
a compiler and compiles a new chunk of code every time you need to access an array?

 

There
is absolutely no reason to use eval to
solve problems like mapping strings or numbers onto objects.  Doing
so dramatically lowers the quality of the code on pretty much every imaginable axis.

 

It
gets even worse when you use eval on
the server, but that’s another post.

 

 

Tags JScript Performance Scripting

Comments (29)

You must be logged in to post a comment.

  1. Dan ShappirIf I were to rewrite the HTML I would implement it as:No eval and also no lookup table that must be kept in sync with the HTML.Speaking of “new Function”, eval’s sibling so to speak, here is an interesting if somewhat extreme example of its use:The local frames were generated using a custom OSP, feeding data directly into the HTML via binding. The user could filter this view by filling in a search form. The way filtering was done was that the OSP would generate an event, intercepted by a JavaScript event handler. If this handler returned false, the specific record was excluded.Fun times.
  2. Log in to Reply
  3. A big problem was performance – the view could contain hundreds, even thousands of records in extreme cases. Thus, it was imperative that the filtering would be as quick as possible. What I did was generate the JavaScript event handler on the fly based on the user’s input. This way I could construct optimal code for evaluating the specific filter expression.
  4. I was a lead developer for an application that was a mixed thin/fat client – some of the data was maintained locally, thus accessible while offline. The rest of the data was online. The way we did it was that the entire UI was DHTML + JavaScript, with some frames generated locally and the others provided by a web server.
  5. BTW, we do use eval a couple of time in the BeyondJS library, but BeyondJS is not you average JavaScript code. One example where we use it is to construct functions on the fly. The reason we use eval instead of “new Function” is because we need to create the function in the current scope.
  6. function setspan(num, text)
    {
    var span = document.all(“myspan” + num);
    if (span != null)
    span.innertext = text;
    }
  7. November 1, 2003 at 5:21 pm
  8. BradleyAnother good way to get an element in the DOM is to use:
    document.getElementById(“myspan” + num);Log in to Reply
  9. Another benefit of this method (over eval or document.all) is that if you accidentally insert two (or more) elements with the same ID into the document, getElementById will always return an element (the first one), while eval (or document.all) will return a collection of all the elements with that ID, possibly causing code that expects a single element to fail.
  10. November 1, 2003 at 10:06 pm
  11. Dan ShappirgetElementById has one significant advantage over document.all – it’s part of the DOM standard endorsed by the W3C, and is thus also supported by Mozilla. On the downside, it not supported by IE4 (not sure if anyone still cares about that version).Log in to Reply
  12. I’m not sure, however, that the fact that it returns the first element in the event of multiple existing elements with the same ID is an advantage. It means that if you accidentally create two elements with the same ID you might not notice and as result not fix the bug.
  13. November 2, 2003 at 4:21 am
  14. Meme WasherIn the comp.lang.javascript Javascript Best Practices document; I came across an interesting discussion of the reasons for preferring square bracket notation to eval(). The consensus seems to be that eval is evil, and that &quot;if it exists in your page,..
  15. Log in to Reply
  16. June 6, 2006 at 8:35 am
  17. Mike’s Lookout » Blog Archive » Disection of a Spam CommentPingBack from http://www.belshe.com/2006/10/25/disection-of-a-spam-comment/
  18. Log in to Reply
  19. October 25, 2006 at 2:19 pm
  20. SteveEval is easy… Hahahahahahah.Also:-Maintainability. Depends on the situtaion. Eval may be better.Memory. Aint a problem.Log in to Reply
  21. I think a lot of of “Gurus” are opposed to anything that makes life easier for us lesser beings.
  22. Speed. If it’s fast enough who cares.
  23. Debugability.   Well if bugs turn up I can always rewrite it the hard way. Also in many cases the eval code may be simpler and more readable.
  24. If  a fly is bugging me and I have a sledgehammer beside me, why go inside for and search for a flyswatter? That might take me half an hour.
  25. November 30, 2006 at 5:35 pm
  26. AlbertoSteve Rocks!Though, going back to the eval thing, it is true that the eval is bad and that there is a number of workarounds (one of the reasons why i love js!).doing eval(‘obj.’ + methodName) seems a piece of cake. What about obj[methodName]() ? Much better.function ClassFactory(constructorClassName){    eval(‘myObj=new ‘ + constructorClassName +'()’)}Log in to Reply
  27. A class factory on the fly!!!
  28.     return myObj;
  29.     var myObj;
  30. Though there is nothing like:
  31. Workaround A: gotta call a method of an object but i know only the name.
  32. I agree, a religious conception of programming is the whorthest evil there is (bracket should be opened on a new line, etc);
  33. January 10, 2007 at 10:57 pm
  34. How to Use window.onload the Right WayPingBack from http://blog.roberthahn.ca/articles/2007/02/02/how-to-use-window-onload-the-right-way
  35. Log in to Reply
  36. February 2, 2007 at 10:01 am
  37. Why Won’t eval() Eval My JSON? (Or: JSON Object !== Object Literal) « The Curious SchemerPingBack from http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
  38. Log in to Reply
  39. March 28, 2007 at 2:14 pm
  40. Template-Engine – Seite 3 – PHP @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & HilfePingBack from http://www.tutorials.de/forum/php/268678-template-engine-3.html#post1415829
  41. Log in to Reply
  42. May 6, 2007 at 4:14 am
  43. Twey— QUOTE —function ClassFactory(constructorClassName){    eval(‘myObj=new ‘ + constructorClassName +'()’)}How about:function ClassFactory(constructorClassName) {}(Although the usefulness of this function is debatable, and the names misleading: there are no classes in JScript.)— CODE — eval(‘myobject.’ + propName + ‘ = ‘ “’ + propValue + ‘”’);// versus— END CODE —* I say “almost” — the example scenarios EricLippert gave are perfectly valid reasons to use eval(), and to write a dedicated JS parser for these situations is (usually) silly when eval() is already available.Log in to Reply
  44. P.S. Ugh, I had to switch browsers to post this — no Konq support on a blog that deals with web coding?
  45. Especially note, if we’re discussing getElementById() support, that some older browsers don’t support try/catch, so the only option when given a bad property name or value is to error out if you want to support these browsers.
  46. myobject.someProperty[propName] = propValue;
  47. } catch(e) {}
  48. try {
  49. Almost* everything that can be done with eval() can be done with square bracket notation, and not only is it more efficient, it’s also almost invariably simpler (you don’t have to worry about whether the input will form a valid JS expression, for a start) and produces neater code than eval():
  50. — END CODE —
  51.  return new this[constructorClassName]();
  52. — CODE —
  53. — END QUOTE —
  54.     return myObj;
  55.     var myObj;
  56. Though there is nothing like:
  57. August 14, 2007 at 4:03 am
  58. 5 Things I Hate About Ruby « Devi Web DevelopmentPingBack from http://deviweb.wordpress.com/2007/09/03/5-things-i-hate-about-ruby/
  59. Log in to Reply
  60. September 3, 2007 at 7:19 am
  61. The best Smarty + Zend View Helpers solution! | CodeUtopiaPingBack from http://codeutopia.net/blog/2007/11/03/the-best-smarty-zend-view-helpers-solution/
  62. Log in to Reply
  63. November 6, 2007 at 12:52 am
  64. Ajax Girl » Blog Archive » Is using a JS packer a security threat?PingBack from http://www.ajaxgirl.com/2008/01/26/is-using-a-js-packer-a-security-threat/
  65. Log in to Reply
  66. January 26, 2008 at 4:32 am
  67. Javascript News » Blog Archive » Is using a JS packer a security threat?PingBack from http://www.javascriptnews.com/javascript/is-using-a-js-packer-a-security-threat.html
  68. Log in to Reply
  69. January 26, 2008 at 12:54 pm
  70. The Best Web Design ComicsPingBack from http://blogsurfer.net/7270/the-best-web-design-comics-13.html
  71. Log in to Reply
  72. January 26, 2008 at 1:04 pm
  73. Is using a JS packer a security threat?PingBack from http://blogsurfer.net/7406/is-using-a-js-packer-a-security-threat-2.html
  74. Log in to Reply
  75. January 27, 2008 at 12:33 am
  76. Is using a JS packer a security threat?PingBack from http://blogsurfer.net/7518/is-using-a-js-packer-a-security-threat-3.html
  77. Log in to Reply
  78. January 27, 2008 at 9:31 am
  79. Don’t build your Web site in a vacuumPingBack from http://blogsurfer.net/7618/dont-build-your-web-site-in-a-vacuum-56.html
  80. Log in to Reply
  81. January 27, 2008 at 5:33 pm
  82. WordPress Admin Theme: DeconstructedPingBack from http://blogsurfer.net/7663/wordpress-admin-theme-deconstructed.html
  83. Log in to Reply
  84. January 27, 2008 at 9:10 pm
  85. Is using a JS packer a security threat?PingBack from http://blogsurfer.net/7923/is-using-a-js-packer-a-security-threat-4.html
  86. Log in to Reply
  87. January 29, 2008 at 12:32 am
  88. Manipulating innerHTML removes eventsPingBack from http://blogsurfer.net/8079/manipulating-innerhtml-removes-events-70.html
  89. Log in to Reply
  90. January 29, 2008 at 2:02 pm
  91. Web Content: Not just YOUR words and picturesPingBack from http://blogsurfer.net/8135/web-content-not-just-your-words-and-pictures-44.html
  92. Log in to Reply
  93. January 29, 2008 at 8:35 pm
  94. Our new additionPingBack from http://blogsurfer.net/8500/our-new-addition-39.html
  95. Log in to Reply
  96. January 31, 2008 at 7:03 am
  97. Performance web &raquo; Archive du blog &raquo; JSON ?PingBack from http://performance.survol.fr/2008/04/json/
  98. Log in to Reply
  99. April 25, 2008 at 1:17 pm
  100. Ajax performance analysis – Blue Box SolsPingBack from http://blueboxsols.com/?p=1813
  101. Log in to Reply
  102. September 10, 2008 at 1:09 pm
  103. Sergio PereiraThis post is part of a series called JavaScript Demystified . I'm pretty sure by now you have heard
  104. Log in to Reply
  105. March 31, 2009 at 6:27 pm
  106. linkfeedr &raquo; Blog Archive &raquo; JavaScript: Avoid the Evil eval – RSS Indexer (beta)PingBack from http://www.linkfeedr.com/development/140126/javascript-avoid-the-evil-eval.html
  107. Log in to Reply
  108. May 22, 2009 at 7:02 pm
  109. mr.tangoh,I can’t understand.my english is pool enough
  110. Log in to Reply
  111. July 13, 2012 at 12:05 am

Eval is evil, part one

The eval method
— which takes a string containing JScript code, compiles it and runs it — is probably
the most powerful and most misused method in JScript. There are a few scenarios in
which eval is
invaluable. For example, when you are
building up complex mathematical expressions based on user input, or when you are
serializing object state to a string so that it can be stored or transmitted, and
reconstituted later.

 

However,
these worthy scenarios make up a tiny percentage of the actual usage of eval. In
the majority of cases, eval is
used like a sledgehammer swatting a fly — it gets the job done, but with too much
power. It’s slow, it’s unwieldy, and
tends to magnify the damage when you make a mistake. Please
spread the word far and wide: if you are considering
using
eval then
there is probably a better way.
Think
hard before you use eval.

 

Let
me give you an example of a typical usage.

 

<span
id=”myspan1″></span>

<span
id=”myspan2″></span>

<span
id=”myspan3″></span>

function
setspan(num, text)

{

eval(“myspan”
+ num + “.innerText = ‘” + text + “‘”);

}

 

Somehow
the program is getting its hands on a number, and it wants to map that to a particular
span. What’s wrong with this picture?

 

Well,
pretty much everything. This
is a horrid way to implement these simple semantics.
First
off, what if the text contains an apostrophe? Then
we’ll generate

 

myspan1.innerText
= ‘it ain’t what you do, it’s the way thacha do it’;

Which
isn’t legal JScript. Similarly, what
if it contains stuff interpretable as escape sequences? OK,
let’s fix that up.

 

eval(“myspan”
+ num).innerText = text;

If
you have to use
eval, eval as
little of the expression as possible, and only do it once.
I’ve
seen code like this in real live web sites:

 

if (eval(foo)
!= null && eval(foo).blah == 123)

eval(foo).baz
= “hello”;

 

Yikes! That
calls the compiler three times to compile up the same code! People, eval starts
a compiler
. Before
you use it, ask yourself whether there is a better way to solve this problem than
starting up a compiler!

 

Anyway,
our modified solution is much better but still awful. What
if num is
out of range? What if it isn’t even a
number? We could put in checks, but why
bother? We need to take a step back here
and ask what problem we are trying to solve.

 

We
have a number. We would like to map that
number onto an object. How would you
solve this problem if you didn’t have eval? This
is not a difficult programming problem! Obviously
an array is a far better solution:

 

var spans
= new Array(null, myspan1, myspan2, myspan3);

function
setspan(num, text)

{

if
(spans[num] != null)

spans[num].innertext
= text;

}

 

And
since JScript has string-indexed associative arrays, this generalizes to far more
than just numeric scenarios. Build
any map you want. JScript even provides
a convenient syntax for maps!

 

var spans
= { 1 : mySpan1, 2 : mySpan2, 12 : mySpan12 };

 

Let’s
compare these two solutions on a number of axes:

 

Debugability:
what is easier to debug, a program that dynamically generates new code at runtime,
or a program with a static body of code? What
is easier to debug, a program that uses arrays as arrays, or a program that every
time it needs to map a number to an object it compiles up a small new program?

 

Maintainability:
What’s easier to maintain, a table or a program that dynamically spits new code?

 

Speed:
which do you think is faster, a program that dereferences an array, or a program that
starts a compiler?

 

Memory:
which uses more memory, a program that dereferences an array, or a program that starts
a compiler and compiles a new chunk of code every time you need to access an array?

 

There
is absolutely no reason to use eval to
solve problems like mapping strings or numbers onto objects. Doing
so dramatically lowers the quality of the code on pretty much every imaginable axis.

 

It
gets even worse when you use eval on
the server, but that’s another post.

 

 

Tags JScript Performance Scripting

Comments (29)

Cancel reply

You must be logged in to post a comment.

  1. Dan Shappir says:If I were to rewrite the HTML I would implement it as:No eval and also no lookup table that must be kept in sync with the HTML.Speaking of “new Function”, eval’s sibling so to speak, here is an interesting if somewhat extreme example of its use:The local frames were generated using a custom OSP, feeding data directly into the HTML via binding. The user could filter this view by filling in a search form. The way filtering was done was that the OSP would generate an event, intercepted by a JavaScript event handler. If this handler returned false, the specific record was excluded.Fun times.
  2. Log in to Reply
  3. A big problem was performance – the view could contain hundreds, even thousands of records in extreme cases. Thus, it was imperative that the filtering would be as quick as possible. What I did was generate the JavaScript event handler on the fly based on the user’s input. This way I could construct optimal code for evaluating the specific filter expression.
  4. I was a lead developer for an application that was a mixed thin/fat client – some of the data was maintained locally, thus accessible while offline. The rest of the data was online. The way we did it was that the entire UI was DHTML + JavaScript, with some frames generated locally and the others provided by a web server.
  5. BTW, we do use eval a couple of time in the BeyondJS library, but BeyondJS is not you average JavaScript code. One example where we use it is to construct functions on the fly. The reason we use eval instead of “new Function” is because we need to create the function in the current scope.
  6. function setspan(num, text)
    {
    var span = document.all(“myspan” + num);
    if (span != null)
    span.innertext = text;
    }
  7. November 1, 2003 at 5:21 pm
  8. Bradley says:Another good way to get an element in the DOM is to use:
    document.getElementById(“myspan” + num);Log in to Reply
  9. Another benefit of this method (over eval or document.all) is that if you accidentally insert two (or more) elements with the same ID into the document, getElementById will always return an element (the first one), while eval (or document.all) will return a collection of all the elements with that ID, possibly causing code that expects a single element to fail.
  10. November 1, 2003 at 10:06 pm
  11. Dan Shappir says:getElementById has one significant advantage over document.all – it’s part of the DOM standard endorsed by the W3C, and is thus also supported by Mozilla. On the downside, it not supported by IE4 (not sure if anyone still cares about that version).Log in to Reply
  12. I’m not sure, however, that the fact that it returns the first element in the event of multiple existing elements with the same ID is an advantage. It means that if you accidentally create two elements with the same ID you might not notice and as result not fix the bug.
  13. November 2, 2003 at 4:21 am
  14. Meme Washer says:In the comp.lang.javascript Javascript Best Practices document; I came across an interesting discussion of the reasons for preferring square bracket notation to eval(). The consensus seems to be that eval is evil, and that &quot;if it exists in your page,..
  15. Log in to Reply
  16. June 6, 2006 at 8:35 am
  17. Mike’s Lookout » Blog Archive » Disection of a Spam Comment says:PingBack from http://www.belshe.com/2006/10/25/disection-of-a-spam-comment/
  18. Log in to Reply
  19. October 25, 2006 at 2:19 pm
  20. Steve says:Eval is easy… Hahahahahahah.Also:-Maintainability. Depends on the situtaion. Eval may be better.Memory. Aint a problem.Log in to Reply
  21. I think a lot of of “Gurus” are opposed to anything that makes life easier for us lesser beings.
  22. Speed. If it’s fast enough who cares.
  23. Debugability.   Well if bugs turn up I can always rewrite it the hard way. Also in many cases the eval code may be simpler and more readable.
  24. If  a fly is bugging me and I have a sledgehammer beside me, why go inside for and search for a flyswatter? That might take me half an hour.
  25. November 30, 2006 at 5:35 pm
  26. Alberto says:Steve Rocks!Though, going back to the eval thing, it is true that the eval is bad and that there is a number of workarounds (one of the reasons why i love js!).doing eval(‘obj.’ + methodName) seems a piece of cake. What about obj[methodName]() ? Much better.function ClassFactory(constructorClassName){    eval(‘myObj=new ‘ + constructorClassName +'()’)}Log in to Reply
  27. A class factory on the fly!!!
  28.     return myObj;
  29.     var myObj;
  30. Though there is nothing like:
  31. Workaround A: gotta call a method of an object but i know only the name.
  32. I agree, a religious conception of programming is the whorthest evil there is (bracket should be opened on a new line, etc);
  33. January 10, 2007 at 10:57 pm
  34. How to Use window.onload the Right Way says:PingBack from http://blog.roberthahn.ca/articles/2007/02/02/how-to-use-window-onload-the-right-way
  35. Log in to Reply
  36. February 2, 2007 at 10:01 am
  37. Why Won’t eval() Eval My JSON? (Or: JSON Object !== Object Literal) « The Curious Schemer says:PingBack from http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
  38. Log in to Reply
  39. March 28, 2007 at 2:14 pm
  40. Template-Engine – Seite 3 – PHP @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & Hilfe says:PingBack from http://www.tutorials.de/forum/php/268678-template-engine-3.html#post1415829
  41. Log in to Reply
  42. May 6, 2007 at 4:14 am
  43. Twey says:— QUOTE —function ClassFactory(constructorClassName){    eval(‘myObj=new ‘ + constructorClassName +'()’)}How about:function ClassFactory(constructorClassName) {}(Although the usefulness of this function is debatable, and the names misleading: there are no classes in JScript.)— CODE — eval(‘myobject.’ + propName + ‘ = ‘ “’ + propValue + ‘”’);// versus— END CODE —* I say “almost” — the example scenarios EricLippert gave are perfectly valid reasons to use eval(), and to write a dedicated JS parser for these situations is (usually) silly when eval() is already available.Log in to Reply
  44. P.S. Ugh, I had to switch browsers to post this — no Konq support on a blog that deals with web coding?
  45. Especially note, if we’re discussing getElementById() support, that some older browsers don’t support try/catch, so the only option when given a bad property name or value is to error out if you want to support these browsers.
  46. myobject.someProperty[propName] = propValue;
  47. } catch(e) {}
  48. try {
  49. Almost* everything that can be done with eval() can be done with square bracket notation, and not only is it more efficient, it’s also almost invariably simpler (you don’t have to worry about whether the input will form a valid JS expression, for a start) and produces neater code than eval():
  50. — END CODE —
  51.  return new this[constructorClassName]();
  52. — CODE —
  53. — END QUOTE —
  54.     return myObj;
  55.     var myObj;
  56. Though there is nothing like:
  57. August 14, 2007 at 4:03 am
  58. 5 Things I Hate About Ruby « Devi Web Development says:PingBack from http://deviweb.wordpress.com/2007/09/03/5-things-i-hate-about-ruby/
  59. Log in to Reply
  60. September 3, 2007 at 7:19 am
  61. The best Smarty + Zend View Helpers solution! | CodeUtopia says:PingBack from http://codeutopia.net/blog/2007/11/03/the-best-smarty-zend-view-helpers-solution/
  62. Log in to Reply
  63. November 6, 2007 at 12:52 am
  64. Ajax Girl » Blog Archive » Is using a JS packer a security threat? says:PingBack from http://www.ajaxgirl.com/2008/01/26/is-using-a-js-packer-a-security-threat/
  65. Log in to Reply
  66. January 26, 2008 at 4:32 am
  67. Javascript News » Blog Archive » Is using a JS packer a security threat? says:PingBack from http://www.javascriptnews.com/javascript/is-using-a-js-packer-a-security-threat.html
  68. Log in to Reply
  69. January 26, 2008 at 12:54 pm
  70. The Best Web Design Comics says:PingBack from http://blogsurfer.net/7270/the-best-web-design-comics-13.html
  71. Log in to Reply
  72. January 26, 2008 at 1:04 pm
  73. Is using a JS packer a security threat? says:PingBack from http://blogsurfer.net/7406/is-using-a-js-packer-a-security-threat-2.html
  74. Log in to Reply
  75. January 27, 2008 at 12:33 am
  76. Is using a JS packer a security threat? says:PingBack from http://blogsurfer.net/7518/is-using-a-js-packer-a-security-threat-3.html
  77. Log in to Reply
  78. January 27, 2008 at 9:31 am
  79. Don’t build your Web site in a vacuum says:PingBack from http://blogsurfer.net/7618/dont-build-your-web-site-in-a-vacuum-56.html
  80. Log in to Reply
  81. January 27, 2008 at 5:33 pm
  82. WordPress Admin Theme: Deconstructed says:PingBack from http://blogsurfer.net/7663/wordpress-admin-theme-deconstructed.html
  83. Log in to Reply
  84. January 27, 2008 at 9:10 pm
  85. Is using a JS packer a security threat? says:PingBack from http://blogsurfer.net/7923/is-using-a-js-packer-a-security-threat-4.html
  86. Log in to Reply
  87. January 29, 2008 at 12:32 am
  88. Manipulating innerHTML removes events says:PingBack from http://blogsurfer.net/8079/manipulating-innerhtml-removes-events-70.html
  89. Log in to Reply
  90. January 29, 2008 at 2:02 pm
  91. Web Content: Not just YOUR words and pictures says:PingBack from http://blogsurfer.net/8135/web-content-not-just-your-words-and-pictures-44.html
  92. Log in to Reply
  93. January 29, 2008 at 8:35 pm
  94. Our new addition says:PingBack from http://blogsurfer.net/8500/our-new-addition-39.html
  95. Log in to Reply
  96. January 31, 2008 at 7:03 am
  97. Performance web &raquo; Archive du blog &raquo; JSON ? says:PingBack from http://performance.survol.fr/2008/04/json/
  98. Log in to Reply
  99. April 25, 2008 at 1:17 pm
  100. Ajax performance analysis – Blue Box Sols says:PingBack from http://blueboxsols.com/?p=1813
  101. Log in to Reply
  102. September 10, 2008 at 1:09 pm
  103. Sergio Pereira says:This post is part of a series called JavaScript Demystified . I'm pretty sure by now you have heard
  104. Log in to Reply
  105. March 31, 2009 at 6:27 pm
  106. linkfeedr &raquo; Blog Archive &raquo; JavaScript: Avoid the Evil eval – RSS Indexer (beta) says:PingBack from http://www.linkfeedr.com/development/140126/javascript-avoid-the-evil-eval.html
  107. Log in to Reply
  108. May 22, 2009 at 7:02 pm
  109. mr.tang says:oh,I can’t understand.my english is pool enough
  110. July 13, 2012 at 12:05 am