# Micro-optimizations in Kotlin -- 2

DevFeed: [Micro-optimizations in Kotlin -- 2](<https://devfeed.tech/articles/micro-optimizations-in-kotlin-2-25600.md>)

Original publisher: [Read original article](<https://www.romainguy.dev/posts/2024/micro-optimizations-in-kotlin-2/>)

Author: Romain Guy

Published: 2024-01-16T00:00:00Z

Content type: tutorial

Language: en

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

Topics: [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [Code](<https://devfeed.tech/topics/code.md>), [inlining](<https://devfeed.tech/topics/inlining.md>), [Android](<https://devfeed.tech/topics/android.md>), [Assembly](<https://devfeed.tech/topics/assembly.md>)

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

## AI overview

This article examines micro-optimizations for Kotlin's Float.sign and Double.sign APIs. It explains their handling of negative and positive values, signed zero, and NaN, then compares the Kotlin implementation with Android's generated AArch64 assembly. The article shows how inlining and intrinsics eliminate function calls and translate the implementation into bit manipulation.

## Source excerpt

In the previous post, we saw how we could micro-optimize Int.sign to save a few instructions. We are now going to turn to Float.sign (and by extension Double.sign). Float.sign returns the sign of single-precision float value as a single-precision float value. While similar to Int.sign, this API must handle a special cases: Not-a-Number (NaN). The exact behavior of the API is that it will return: -1.0f if the value is negative +/-0.0f if the value is zero (floats can encode both positive and negative zero) 1.0f if the value is positive NaN if the value is NaN An easy way to implement this API ourselves is to return the input when the input equals 0.0f or NaN, and to return the input's sign copied onto 1.0f otherwise. Translated to code, we can write: