elye
02/28/2024, 1:11 PMfun CharSequence.isMyBlank(): Boolean {
return indices.all { this[it].isWhitespace() }
}
It seems slower than when I have it as
fun CharSequence.isMyBlank(): Boolean {
return indices.all { this[it].isWhitespace() }
}
public val CharSequence.indices: IntRange
get() = 0..length - 1
Even though the indices
implementation above is the same as Kotlin provided one.
Anyone know why?
A more illustrated question is provided in https://stackoverflow.com/questions/78074675/why-my-identical-indices-implementation-is-faster-than-the-kotlin-provided-oneYoussef Shoaib [MOD]
02/28/2024, 1:27 PMSzymon Jeziorski
02/28/2024, 1:28 PMfun CharSequence.isMyBlank(): Boolean = indices.all { this[it].isWhitespace() }
fun CharSequence.isMyBlank2(): Boolean = indices2.all { this[it].isWhitespace() }
val CharSequence.indices2: IntRange
get() = 0..length - 1
@State(Scope.Benchmark)
class IsBlankBenchmark {
private val strings = listOf(" ", "random string", "_", " ")
@Benchmark
fun isMyBlank() = strings.map { it.isMyBlank() }
@Benchmark
fun isMyBlank2() = strings.map { it.isMyBlank2() }
}
results:
benchmarks summary:
Benchmark Mode Cnt Score Error Units
IsBlankBenchmark.isMyBlank avgt 3 52.768 ± 1.392 ns/op
IsBlankBenchmark.isMyBlank2 avgt 3 53.414 ± 2.537 ns/op
As you can see, there is pretty much no viable difference whatsoever