Derek Peirce
03/05/2026, 7:31 AMcount(predicate) extension method is written for each type as:
public inline fun ByteArray.count(predicate: (Byte) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) ++count
return count
}
However, this could be improved by instead writing it as:
public inline fun ByteArray.count(predicate: (Byte) -> Boolean): Int {
var count = 0
for (element in this) count += if (predicate(element)) 1 else 0
return count
}
This is because the compiler can easily convert the ternary 1/0 as a boolean-to-int cast, and avoid using branches altogether, paying no penalty for missed predictions.
I ran a benchmark comparing the two implementation on a random 100,000 bytes (using Java Microbenchmark Harness), counting either 0s or even numbers, and got these results:
Benchmark Mode Cnt Score Error Units
CountBenchmark.countEvensAsInt avgt 20 44.290 ± 0.879 us/op
CountBenchmark.countEvensBuiltin avgt 20 53.830 ± 0.974 us/op
CountBenchmark.countZerosAsInt avgt 20 28.937 ± 0.811 us/op
CountBenchmark.countZerosBuiltin avgt 20 17.543 ± 0.136 us/op
That's a fairly significant reduction in count overhead.CLOVIS
03/05/2026, 8:00 AMDerek Peirce
03/05/2026, 8:12 AMif (boolValue) ++variable and turning into variable += if (boolValue) 1 else 0 when variable is guaranteed to be quickly accessible and not an object field or array value, but I expect improving the count method, at least at first, would be faster.CLOVIS
03/05/2026, 8:27 AMDerek Peirce
03/05/2026, 8:41 AMCLOVIS
03/05/2026, 9:02 AMCLOVIS
03/05/2026, 9:03 AMDerek Peirce
03/05/2026, 9:33 AMBenchmark Mode Cnt Score Error Units
ScrabbleBenchmark.kotlinScrabbleFunctional avgt 20 368.605 ± 14.725 ms/op
ScrabbleBenchmark.kotlinScrabbleImperative avgt 20 263.723 ± 12.468 ms/op
When I ran this about six years ago on a different machine, imperative was a 13% time reduction. Here, it's a 29% time reduction.CLOVIS
03/05/2026, 9:52 AMCLOVIS
03/05/2026, 9:53 AMvalue class are currently in discussion, this may be a relevant point to thoseDerek Peirce
03/05/2026, 7:26 PM