Mon 16 Apr 2007
Sometimes the management asks: Why do we need to hire Java programmers, can
we not let our scripters do the job?
Ok, you can answer this question by using a lot of buzzwords. But it seems to me to be more difficult to explain it to someone who has not at least a basic insight into the programming domain. Here is a (too?) simple java example:
/* straight forward coding you will see suprisingly often done by people with scripting background only, creates 1000 copies of "D" */
String[] a = new String[1000];
for (int i = 0; i < 1000; i++) {
a[i] = new String("D");
}/* creates 1 instance of "D" and 1000 references to it,
in more serious operations that will have visible effect on the performance */
String[] a = new String[1000];
String d = "D";
for (int i = 0; i < 1000; i++) {
a[i] = d;
}/* So what about this? */
String[] a = new String[1000];
for (int i = 0; i < 1000; i++) {
a[i] = "D";
}
/* Actually the compiler will treat "D" as a static symbol, no overhead is produced
*/All literal strings and string-valued constants are kept in a pool maintained privately by the class String. You can use String.intern() to add you own strings to this pool. If the pool already contains a string equal to your String object, as determined by the equals(Object) method, then the string from the pool is returned, otherwise your String object is added to the pool and a reference to it is returned.
Check it out by yourself:
/**
* @see http://java.sun.com/docs/books/performance/1st_edition/html/JPRAMFootprint.fm.html
* @author Konstantin Rekk
*
*/
public class InitialisationIssues { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stubString[] a = new String[1000];System.out.println("before: " + getUsedMemory());
// String d = new String("-----DATA-----------------------------");
for (int i = 0; i < 1000; i++) {
// a[i] = new String("-----DATA-----------------------------"); ;
a[i] = "-----DATA-----------------------------";
}
System.out.println("after: " + getUsedMemory());
for (String el : a) {
System.out.println(el.toString());
}
}
private static long getUsedMemory() {
gc();
long totalMemory = Runtime.getRuntime().totalMemory();
gc();
long freeMemory = Runtime.getRuntime().freeMemory();
long usedMemory = totalMemory - freeMemory;
return usedMemory;
}
private static void gc() {
try {
System.gc();
Thread.sleep(100);
System.runFinalization();
Thread.sleep(100);
System.gc();
Thread.sleep(100);
System.runFinalization();
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}