
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
58 lines
2.0 KiB
Plaintext
58 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
An ``++indexOf++`` or ``++lastIndexOf++`` call with a single letter ``++String++`` can be made more performant by switching to a call with a ``++char++`` argument.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
String myStr = "Hello World";
|
|
// ...
|
|
int pos = myStr.indexOf("W"); // Noncompliant
|
|
// ...
|
|
int otherPos = myStr.lastIndexOf("r"); // Noncompliant
|
|
// ...
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
String myStr = "Hello World";
|
|
// ...
|
|
int pos = myStr.indexOf('W');
|
|
// ...
|
|
int otherPos = myStr.lastIndexOf('r');
|
|
// ...
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Put single-quotes around 'x' to use the faster "indexOf(char)" method.
|
|
* Put single-quotes around 'x' to use the faster "lastIndexOf(char)" method.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 18 Mar 2016, 10:46:21 Michael Gumowski wrote:
|
|
\[~ann.campbell.2] I removed the reference to ``++pmd:SimplifyStartsWith++`` and updated the RSPEC to only target ``++indexOf++``/``++lastIndexOf++``, as replacing ``++str.startWith("c")++`` by ``++!str.isEmpty && str.charAt(0) == 'c'++`` is really controversial (3 operations instead of 1? proof of efficiency should be done). Note that I didn't created a new RSPEC to cover that newly unmapped pmd rule. Similarly, the CodePro mapping is not valid anymore.
|
|
|
|
|
|
The part regarding ``++indexOf++`` is however still pretty valid and should be activated by default.
|
|
|
|
=== on 6 May 2020, 10:47:50 Johann Beleites wrote:
|
|
It seems as though this rule is not relevant (anymore). It is hard to find evidence that supports indexOf(char) being faster than indexOf(String). On the contrary, in current Java versions, you can collect evidence that points to the opposite being true. In either case, performance differences are not huge. In any case, it does not generally seem better to use the char instead of the String version of indexOf. Hence, I have deprecated this rule (see SONARJAVA-3339).
|
|
|
|
endif::env-github,rspecator-view[]
|