Subj : Re: Performance: Another test of Java vs JavaScript ... To : Neil Kolban From : Igor Bukanov Date : Fri Oct 17 2003 07:52 pm If you replace the tests by: public class Perf2 { public static void main(String[] args) { String string = "ABCDEFGHIJ"; int i = 1; long start = System.currentTimeMillis(); int length = 0; while (i<200000) { length += String.valueOf(i).length(); i = i + 1; } long diff = System.currentTimeMillis() - start; System.out.println("Elapsed: " + diff+" length="+length); } } and function myFunc() { var time = (new Date()).getTime(); var string = "ABCDEFGHIJ"; var sub; var i; i = 1; var length = 0; while (i < 200000) { length += String(i).length; i = i + 1; } time = (new Date()).getTime() - time; print("time: "+time+"ms length="+length); } myFunc(); then on my Linux box and jdk 1.4.2 I got for Java 145ms and for JS 1434ms while for the original case it was 42 versus 1227. It seems Java compiler/JVM was smart enough to optimize away the constant expression as Sterling pointed above. Neil Kolban wrote: > Folks, > > Here are a couple of code fragments.... the first is Java and the 2nd is > JavaScript running under Rhino. > > ------------------------------------------------------------------------ > * * > > *public* *class* Perf2 { > *public* *static* *void* main(String[] args) { > String string = "ABCDEFGHIJ"; > String sub; > *int* i = 1; > *long* start = System.currentTimeMillis(); > * while* (i<200000) > { > sub = string.substring(3,6); > i = i + 1; > } > * long* diff = System.currentTimeMillis() - start; > System.out.println("Elapsed: " + diff); > } > } > > ------------------------------------------------------------------------ > > * * > > *function* myFunc() > { > * var* string = "ABCDEFGHIJ"; > * var* sub; > * var* i; > i = 1; > * while* (i < 200000) > { > sub = string.substring(3, 6); > i = i + 1; > } > } > > myFunc(); > > ------------------------------------------------------------------------ > > The Java program takes 15 milliseconds, the JavaScript takes 850 > milliseconds. I understand compiled Java will probably be faster but I > am surprised at how much faster. > .