Skip to content

Make AutoBoxingBenchmark cache test use the Integer cache - #375

Open
noisegain wants to merge 1 commit into
android:mainfrom
noisegain:fix-autoboxing-benchmark
Open

noisegain wants to merge 1 commit into
android:mainfrom
noisegain:fix-autoboxing-benchmark

Conversation

@noisegain

Copy link
Copy Markdown

integerArtCacheAlloc is documented as measuring "the cost of allocating a boxed integer that takes advantage of ART's cache", but it never reaches the cache.

The test creates its values with the Integer constructor (Integer(i.toInt() + 1)), which always allocates a new object.
Only Integer.valueOf() / autoboxing can return a cached instance.
The test body has been written this way since the test was added.

Replacing the constructor with plain autoboxing inside the measureRepeated block is not enough with the current benchmark library.
With androidx.benchmark 1.4.0 the block is compiled into a suspend lambda, and in coroutine code the Kotlin compiler boxes primitives through kotlin.coroutines.jvm.internal.Boxing (https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/src/kotlin/coroutines/jvm/internal/boxing.kt), which calls the Integer constructor instead of Integer.valueOf().
Boxing done directly in the block therefore still allocates on every iteration.

This PR moves the boxing into two regular (non-inline) helper functions, where the compiler emits Integer.valueOf(), and adds a comment explaining why they have to stay that way.

Verification

Allocations per iteration (allocationCount median from the benchmark JSON), Samsung Galaxy S24+ (SM-S926B), Android 17, compilationMode = speed, Kotlin 2.2.0 (2.1.10 for the 1.3.3 rows):

Test body androidx.benchmark integerArtCacheAlloc integerAlloc
original (Integer(...)) 1.3.3 1 1
original (Integer(...)) 1.4.0 1 1
autoboxing inside the block 1.3.3 0 0.99
autoboxing inside the block 1.4.0 1 1
this PR 1.4.0 0 1

The 1.3.3 rows were measured on c0b3985; the 1.4.0 rows on current main.
Each row is a single run.

The bytecode matches the numbers (javap -c):

  • with 1.3.3 the block is inlined into the test method and autoboxing compiles to Integer.valueOf()
  • with 1.4.0 the same source ends up in ...$$inlined$measureRepeated$1.invokeSuspend and compiles to Boxing.boxInt()

To reproduce: main currently does not compile (see #373), and on this device the tests do not start without setting a target SDK for the test APK (see #374).
Both fixes were applied locally for every run, together with androidx.benchmark.profiling.mode=None.

@noisegain
noisegain requested a review from a team as a code owner November 18, 2026 16:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant