Skip to content

SONARJAVA-5587 S4635 Add benchmark for Java #5089

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 30, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions rules/S4635/java/rule.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,57 @@ str.substring(beginIndex).indexOf(char1); // Noncompliant; a new String is going
str.indexOf(char1, beginIndex) - beginIndex; // index for char1 not found is (-1-beginIndex)
----

== Resources

=== Benchmarks

[options="header"]
|===
| Method| stringSize| Runtime| Average time| Error margin
| indexOfOnly| 10| Temurin 21| 1.55 ns/op| ±0.12 ns/op
| indexOfOnly| 100| Temurin 21| 1.78 ns/op| ±0.05 ns/op
| indexOfOnly| 1000| Temurin 21| 1.82 ns/op| ±0.18 ns/op
| indexOfOnly| 10000| Temurin 21| 1.77 ns/op| ±0.08 ns/op
| substringThenIndexOf| 10| Temurin 21| 4.85 ns/op| ±0.41 ns/op
| substringThenIndexOf| 100| Temurin 21| 6.22 ns/op| ±0.40 ns/op
| substringThenIndexOf| 1000| Temurin 21| 14.22 ns/op| ±1.66 ns/op
| substringThenIndexOf| 10000| Temurin 21| 275.00 ns/op| ±20.49 ns/op
|===

*Benchmarking code*

The results were generated by running the following snippet with https://github.com/openjdk/jmh[JMH].

[source,java]
----
@BenchmarkMode({Mode.AverageTime})
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class S4635 {
@Param({"10", "100", "1000", "10000"})
int stringSize;

String input;

@Setup
public void setup() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < stringSize; i++) {
builder.append('a');
}
input = builder.toString();
}

@Benchmark
public int substringThenIndexOf() {
return stringSize / 2 + input.substring(stringSize / 2).indexOf('a');
}

@Benchmark
public int indexOfOnly() {
return input.indexOf('a', stringSize / 2);
}
}
----

include::../rspecator.adoc[]