The rule java:S3027 claims that the usage of String.indexOf(char) performs better than String.indexOf(String) and should be used when searching for single characters.
performs better than
I wanted to see the significance of this and wrote a small test program.
The result was quite surprising, because it showed that the opposite is true:
String.indexOf(String) performs magnitudes better than indexOf(char).
I tested with
- Oracle JDK 1.8
- OpenJdk 11
- OpenJdk 13
on my Windows notebook. The result was always similar: indexOf(String) was several 1000 times faster than indexOf(char).
I do not claim this to be anything close to a scientific approach, but the huge difference in the results, worry me anyhow.
The rule seems to be valid for String.lastIndexOf(String), but not as significant as I expected.
Question to the SonarQube team:
What is the rationale behind “blaming” the indexOf(String) function?
Was it true for older JDKs?
IndexOfTesting.txt (946 Bytes)