Wednesday, September 24, 2014

JAVA: Be careful with String class – Performance and Memory

 

1. Operation such as

- String.split()

- String.substring()

uses offset values but keep the ORIGINAL char[] value. Therefore, if you only ever want a portion of the String it will WASTE memory space by storing the original string value

http://stackoverflow.com/questions/7629208/substrings-and-garbage-in-java-1-6

2.  For String.substring()

to get just the portion of the substring, recommend to use

String sub = new String(str.substring(6,12));

http://stackoverflow.com/questions/1281549/memory-leak-traps-in-the-java-standard-api/1281569#1281569


3. General String related:


http://www.javamex.com/tutorials/memory/string_memory_usage.shtml

JAVA: Be careful with String class - General

 

1. JAVA only puts primitive and reference variable onto Stack while all objects, including String, is created and stays on the Heap, subject to GC

http://programmers.stackexchange.com/questions/65281/stack-and-heap-memory-in-java/65289#65289

 

2. String literal value assignment such as

String str1 = “abcd”;

and String variable assignment such as

String str2 = str1

will create these new String objects (which are reference objects) and both str1 and str2 will point to the same object with value “abcd” in the JVM’s internal String Pool

 

3. String Value Object itself, not the reference that points to it, is IMMUTABLE (i.e.the String Class itself is ‘final’), meaning the whenever you try to

String str = someOpToModify(str);

What happens is that another String Value Object is created on the String Pool and this ‘str’ String Reference Object is not changed to point at this new String Value Object rather than the old String Value Object that contains the old value before modification.

http://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning/17942294#17942294

 

4. Only way to make sure a new Object of String is created in the String Pool is to call: String str3 = new String(“abcd”);

5. Why to make the String immutable?

http://stackoverflow.com/questions/2068804/why-is-string-final-in-java/2069014#2069014

  1. Security: the system can hand out sensitive bits of read-only information without worrying that they will be altered
  2. Performance: immutable data is very useful in making things thread-safe.

 

 

All and all, be very careful with String in JAVA, especially when it comes to performance and if you have a lot of long Strings to load into the memory:

http://www.javamex.com/tutorials/memory/string_saving_memory.shtml