forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewStringString.qhelp
More file actions
47 lines (36 loc) · 1.47 KB
/
NewStringString.qhelp
File metadata and controls
47 lines (36 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!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>