# Optimizing Rectangle-Overlap Tests by Removing Conditional Branches

DevFeed: [Optimizing Rectangle-Overlap Tests by Removing Conditional Branches](<https://devfeed.tech/articles/down-a-rabbit-hole-25596.md>)

Original publisher: [Read original article](<https://www.romainguy.dev/posts/2024/down-a-rabbit-hole/>)

Author: Romain Guy

Published: 2024-05-18T00:00:00Z

Content type: tutorial

Language: en

Sources: [Posts on Romain Guy](<https://devfeed.tech/sources/posts-on-romain-guy.md>)

Topics: [Optimization](<https://devfeed.tech/topics/optimization.md>), [Code](<https://devfeed.tech/topics/code.md>), [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [R8](<https://devfeed.tech/topics/r8.md>), [Benchmark](<https://devfeed.tech/topics/benchmark.md>)

Tags: [android](<https://devfeed.tech/tags/android.md>), [assembly](<https://devfeed.tech/tags/assembly.md>), [benchmark](<https://devfeed.tech/tags/benchmark.md>), [code](<https://devfeed.tech/tags/code.md>), [developer](<https://devfeed.tech/tags/developer.md>), [graphics](<https://devfeed.tech/tags/graphics.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [optimization](<https://devfeed.tech/tags/optimization.md>), [performance](<https://devfeed.tech/tags/performance.md>), [r8](<https://devfeed.tech/tags/r8.md>)

## AI overview

This article examines optimizing rectangle-overlap tests in Kotlin. It compares generated assembly, replaces logical operators with bitwise operators to remove conditional branches, and reports a 1.7x speedup in a benchmark on a Google Pixel 6.

## Source excerpt

I recently discussed an optimization that I worked on following Leland's successful nerd snipe. That, however, was not the end of it. He also needed to test for intersecting/overlapping rectangles. The most obvious way to achieve this is pretty straightforward: 1// A rectangle is defined by its left (l), top (t), 2// right (r), and bottom (b) coordinates 3data class Rect(val l: Int, val t: Int, val r: Int, val b: Int) { 4 fun overlaps(other: Rect) = 5 l < other.r && other.l < r && t < other.b && other.t < b 6} The source code is nice and tidy, but the generated assembly is less than ideal (as always, the code was optimized with R8 first):