Along the lines of an existing thread, The “Why” behind PMD's rules, I'm trying to figure out the meaning of one particular PMD rule : String and StringBuffer Rules.StringInstantiation.
This rule states that you shouldn't explicitly instantiate String objects. As per their manual page :
Avoid instantiating String objects; this is usually unnecessary since they are immutable and can be safely shared.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.strings.StringInstantiationRule
Example(s):
private String bar = new String("bar"); // just do a String bar = "bar";
http://pmd.sourceforge.net/pmd-5.0.1/rules/java/strings.html
I don't see how this syntax is a problem, other than it being pointless. Does it affect overwhole performance ?
Thanks for any thought.
With String foo = "foo"
there will be on instance of "foo" in PermGen space (This is referred to as string interning). If you were to later type String bar = "foo"
there would still only be one "foo" in the PermGen space.
Writing String foo = new String( "foo" )
will also create a String
object to count against the heap.
Thus, the rule is there to prevent wasting memory.
Cheers,