Java vs. JavaScript coding
March 13, 2010 5 Comments
In today’s web programming many Java developers write JavaScript coding hence they tend to follow Java best practice and coding style in JavaScript as well. But there is huge amount of difference in both the coding style and best practices.
Lets take a simple example of looping an array in Java.
String perfArray[] = new String[1000];
//style 1
for (int i=0; i < perfArray.length; i++) {
// do something
}
//style 2
int arrayLength = perfArray.length;
for (int i=0; i < arrayLength; i++) {
// do something
}
As shown above both the styles are acceptable and work well. The style 1 is coding is better readability and maintainability compares to style 2. Both the style of code gives the same performance when executing in JVM.
Let take a similar example for JavaScript coding:
var perfArray = new Array();
//style 1
for (var i=0; i < perfArray.length; i++) {
// do something
}
//style 2
var arrayLength = perfArray.length;
for (var i=0; i < arrayLength; i++) {
// do something
}
The style 2 code performance is much better than style 1 in Internet Explorer 8 and Google Chrome browsers. In Mozilla Firefox it is not much difference.
Be cautious if your application contains many JavaScript code.
Can you confirm the best option, you have chosen, to be best performant as well ?
Agnostic of the language, if you write the for loop as follows
for (int i=0; i < perfArray.length; i++)
It would definitely hit the performance to some extent. Consider fetching the length of the array for every iteration, per say, in our example it's 1000.
Yes, the style 2 is the best practice for all languages. The performance impact in Java is less (not worth to optimize), whereas in JavaScript is very high.
Honestly, unless you are going to write map.google.com.. kind of application. I would advise not to focus these kind of tiny gains. Javascript engines should be smart enough to optimize.
Focus where the bang for buck.
//Style 2.1
String perfArray[] = new String[1000];
for (int i=0, len=perfArray.length; i < len; i++) {
// do something
}
Might want to check out EmEditor too. This is the tool I use for 99.99% of my development work. Its one of those thngis that once you gets used to something its hard to breakaway. I’ve been using EmEditor for over 8 years now and can’t seem to get used to anything else.