Reducing the memory consumption of your Java application (Part II)
Check also my new blog at http://kohlerm.blogspot.com/
This is the second part of my series about how to reduce the memory consumption of your Java application. Part I can be found Reducing the memory consumption of your Java application (Part I).
Some comments about my last blog. I’m speaking about JDK 1.4.2 here, because this is what is used today by Netweaver04(s). The rules for JDK 1.5,or JDK 1.6 are different, the general rule being, that there’s less sharing of char’s in the newer JDK’s. Finding out the exact rules for the newer JDK’s is left as an exercise for the reader 😉
Another important function in String is substring(). If you call substring on an existing object this will result in a new String object being created (Strings are immutable), which shares the char of the existing String.
This is in general a good thing, because it allows you to save some memory. If you have for example a path of a file name like “/netweaver/is/great.txt”, then you can have one String object for the whole path and construct another String object for the filename “great.txt” that shares the existing char.
But, you can also easily shoot yourself into the feet :
String fileName="a picture with pretty long file name.jpg"; int length=fileName.length(); String fileType=fileName.substring(length-3,length); return fileType;
The intent of this “beautiful” code is to get the type of the file. The problem with this code is that the original String referenced by “fileName” will not be referenced anymore after the method returns the file type. You will end up with a String being returned with the char “a picture with pretty long file name.jpg”, which is 41 characters versus the 3 characters you really need for “jpg”.
There are even people out there that think, that this is a bug, but as I tried you to explain this is really a feature that can help you to reduce memory consumption.
UPDATE: as Frank pointed out (see comments below) this is even more confusing, than I thought in the first place. There are 2 similiar constructors in String :
public String(char value, int offset, int count)
String(int offset, int count, char value)
The later is called by substring.