Friday, November 17th, 2006
Optimize String Manipulations by Avoiding Intermediate Results
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).
Posted by Dion Almaer at 6:30 am