| [ Web Proxy ] |
| Viewing: https://raw.githubusercontent.com/github/codeql/main/java/ql/src/Performance/NewStringString.qhelp | [Back] [Original] |
The String 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 String object or construct a new instance based on
an existing string, for example by writing something like String hello =
new String("hello"). Furthermore, this practice is not memory efficient.
The copied string is functionally indistinguishable from the argument that
was passed into the String 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.
The following example shows three cases of copying a string using the String
constructor, which is inefficient. In each case, simply removing the constructor call
new String and leaving the argument results in better code and less
memory churn.
| Web Proxy Viewer | New URL | Original Page |