One of the primary goals of weblaster was to have a fast javascript based application to manage a media collection.
The amount of data we are talking about is an array with around 35.000 elements that contain something like this:
{
"id":"10098",
"track_name":"Sarah Yellin'",
"album_name":"Live Away From The Sun",
"artist_name":"3 Doors Down"
}
that’s around 110 bytes per element times 35K nearly 400K of Javascript. If you load this data with an ajax call, the browser will hog your CPU until Firefox goes gray and won’t recover. (Tested on a 4th generation Macbook Pro with 2 GB RAM, 2.4 Core duo. Believe me, even that can’t handle it). The slowness of eval() is to blame for this. You just can’t eval() such a large array, without blocking the browser. The solution that I used in weblaster for this problem was to embed the array into the page it self. The first few lines in the index.php file shows this.
<script type="text/javascript"> tracks = <?= echo json_encode(data); ?> </script>
This way the array is loaded and parsed during the execution of the scripts on the page in the current runtime.
Another optimization technique that is well known is the reverse style array iteration. When iterating over large arrays, looking up the arrays length on the conditional check of the for loop is a large performance hit, especially if the array is a global variable.
So the iteration over the arrays are like this:
for (i=array.length-1;i>=0;i++) {
do_something();
}
2 Comments
http://blogs.sun.com/greimer/entry/best_way_to_code_a
the page in the link above contains some tricks that improves performance of iterations..
@azer great link, very interesting results.
Post a Comment