java.lang.String intern() tweak :
Why String.intern() is useful?
According to Java Docs
When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equal(object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.Now let's tweak above statement by providing some example:
String string1 = "abc";//goes to String pool
//Create new String on heap ,not maintained by pool
String string2 = new String("abc");
String string3 = new String("abc").intern();//good practice ??
System.out.println(string1 == string2); //Of course false(pool vs heap)
System.out.println(string2 == string3);//False,
//string 3 is new but added to pool
//Next statement is worth looking for
System.out.println(string1 == string3);//True, how come??
Well java docs says after creating new String , string3 sits into pool and so is string 1 with same value hence returns true.
Now as developer we see ,it's quite useful to use intern because we will be saving memory as it will avoid holding duplicates entries of String in pool .
Till now everything looks good but(there is always , isn't it?) this also boils down some issues:
1) Locating or Searching a string over pool when there are millions of strings , might slows down searching.
2) String.intern() is native call ,so implementation/algorithm is behind curtain.
My take would be, to use intern() to avoid duplicates in pool and saving some memory and hence some bucks .
No comments:
Post a Comment