Files
codeql/java/ql/src/Performance/NewStringString.qhelp
Marcono1234 e21cbe82a9 Update Java documentation links to Java 11
Where possible update Java documentation links to Java 11.
Additionally update some other links to use HTTPS.
2021-02-26 00:43:51 +01:00

48 lines
1.5 KiB
XML

<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>The <code>String</code> class is immutable, which means that there is
no way to change the string that it represents. Consequently, there is rarely a
need to copy a <code>String</code> object or construct a new instance based on
an existing string, for example by writing something like <code>String hello =
new String("hello")</code>. Furthermore, this practice is not memory efficient.</p>
</overview>
<recommendation>
<p>The copied string is functionally indistinguishable from the argument that
was passed into the <code>String</code> constructor, so you can simply omit the constructor call and
use the argument passed into it directly. Unless an explicit copy of the argument string is needed,
this is a safe transformation.</p>
</recommendation>
<example>
<p>The following example shows three cases of copying a string using the <code>String</code>
constructor, which is inefficient. In each case, simply removing the constructor call
<code>new String</code> and leaving the argument results in better code and less
memory churn.</p>
<sample src="NewStringString.java" />
</example>
<references>
<li>
J. Bloch, <em>Effective Java (second edition)</em>,
Item 5.
Addison-Wesley, 2008.
</li>
<li>
Java API Specification:
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#%3Cinit%3E(java.lang.String)">String(String)</a>.
</li>
</references>
</qhelp>