JavaScript Code Inefficiencies from the IE team

Written by on November 17th, 2006 in Ajax News.

Peter Gurevich has stepped up with another post on IE+JavaScript Performance Recommendations Part 2: JavaScript Code Inefficiencies.

The post is itself part one of a two parter, so this is 2.1 if you will, and covers inefficiencies in Javascript code:

Optimize String Manipulations by Avoiding Intermediate Results

Use Array.join('') over constantly += them together (as long as there is enough stringing going on (very rough: 7 - 13 values). A sample script that tells you the winner is included.

Running Code Using the ‘eval’ Statement is Expensive

The eval statement in JScript is both expensive in terms of performance and prone to error if the site is generating dynamically the script to be run. If you can remove it from your application you should do so. You’ll need to replace it with functional equivalents where the dynamically evaluated code can be simulated by changing the input parameters. This general wisdom not only leads to faster code in most cases but can also make your program more reliable and easy to understand. If arbitrary code is executing on the client machine it becomes hard to determine how it failed.

For those interested in the “why”, execution of an arbitrary string of script involves the construction of a new script runtime, copying the context of the currently executing script, manipulation of the runtime stack, and a bit of other work. This isn’t much different from running other code, but isn’t nearly as fast as writing the inline branching code to handle all of the possibilities of the dynamically generated code. There are obviously good uses for the eval statement, just examine your project thoroughly before taking a dependency on it.

Requirements of Eval for JSON Expressions

With JSON you will be using eval. Keep the data sizes small.

Switch Blocks are Linear Evaluation Tables

If you have a large switch it is best to break this down into a series of nested if statement comparisons, an array where you can perform a binary search, or my personal favorite a sparse array (hash-table).

Source: Ajaxian
Original Article: http://ajaxian.com/archives/javascript-code-inefficiencies-from-the-ie-team

Leave a Reply

You must be logged in to post a comment.



Site Navigation