36 lines
1.3 KiB
Plaintext
36 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Looking for a given substring starting from a specified offset can be achieved by such code: ``++str.substring(beginIndex).indexOf(char1)++``. This works well, but it creates a new ``++String++`` for each call to the ``++substring++`` method. When this is done in a loop, a lot of ``++Strings++`` are created for nothing, which can lead to performance problems if ``++str++`` is large.
|
|
|
|
|
|
To avoid performance problems, ``++String.substring(beginIndex)++`` should not be chained with the following methods:
|
|
|
|
* ``++indexOf(int ch)++``
|
|
* ``++indexOf(String str)++``
|
|
* ``++lastIndexOf(int ch)++``
|
|
* ``++lastIndexOf(String str)++``
|
|
* ``++startsWith(String prefix)++``
|
|
|
|
For each of these methods, another method with an additional parameter is available to specify an offset.
|
|
|
|
Using these methods will avoid the creation of additional ``++String++`` instances.
|
|
For indexOf methods, adjust the returned value by subtracting the substring index parameter to obtain the same result.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
str.substring(beginIndex).indexOf(char1); // Noncompliant; a new String is going to be created by "substring"
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
str.indexOf(char1, beginIndex) - beginIndex; // index for char1 not found is (-1-beginIndex)
|
|
----
|
|
|
|
include::../rspecator.adoc[]
|