Site Search:



Calendar

March 2008
M T W T F S S
« Feb   Apr »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Javascript Coding - Commas before or after lists of objects?

Interesting discussion going on over at the EXT forums at the moment re a new convention that has sprung up with putting the seperating comma at the begging of a line rather than the end with a list of value-pairs in an object - under the proviso that if an error occurs in Internet Explorer - the line that IE detects the error on will be the line with the surpurflous comma. Take a look at the thread for more info…

I was interested in profiling the differences between the two, as logically having the comma on the following line forces the javascript interpreter to have to do more guess work as to whether the previous line is supposed to terminate or continue (javascript automatically does this check for each line to enable developers to leave out semicolons). Thats the theory anyway.

Interesting though. From my ‘experiment’ it appears (as expected) that putting commas before items rather than after does have an effect on the interpreter - average 74ms on my quad core machine (in firefox). Keep in mind though that this object has 300,001 properties which is huge for a javascript object. I don’t think anybody is going to cry over a lost 74ms when creating an object with that many properties. Still - this kind of thing might have a larger impact on less powerful devices such as handhelds.

See below for the results of my experiment:


Okay… so I decided to do a little test over my lunchbreak. Keep in mind that with almost all profiling its completely subjective as cosmic rays hitting my processor could affect the results - but here is what I got anyway:

 

Code:

	Average		Min	Max
After	1434.8ms	1382ms	1498ms

Before	1508.1ms	1434ms	1680ms

I ran the below tests 10 times each using the firebug profiler. Whilst there is a difference I doubt many people would be creating objects with 300,000 boolean properties :p

This was to create a simple object with 300,000 properties in both styles. The code I used for this is:

COMMA BEFORE:

 

PHP Code:

<html>
<head>
<title>JS Profile</title>
</head>
<body>
<button onClick=”eval(document.getElementById(’objectCode’).innerHTML);”> Click Me!</button>
<div id=”objectCode”>
var k = {
“First Item”: false
<?php
for($x=0;$x<300000;$x++){
echo
“, \”item$x\”: true “;
}
?>
}
</div>
</body>
</html>

 

COMMA BEFORE:

PHP Code:

<html>
<head>
<title>JS Profile</title>
</head>
<body>
<button onClick=”eval(document.getElementById(’objectCode’).innerHTML);”> Click Me!</button>
<div id=”objectCode”>
var k = {
<?php
for($x=0;$x<300000;$x++){
echo
“\”item$x\”: true, “;
}
?>
“First Item”: false
}
</div>
</body>
</html>

You can leave a response, or trackback from your own site.

Leave a Reply


precariousPanther Web Blog is proudly powered by WordPress