04
Medium Kotlin
作者:Abdullahkhan
發布:02-14 11:49
The Hidden Cost of Kotlin’s Nullable Primitives
Int?, Float?, and Double? can quietly slow down your hot paths.
重點摘要
Nullable primitives are boxed to reference types at runtime
Boxing introduces allocations, indirection and null checks
Performance regressions appear in tight loops and hot paths
Kotlin allows primitive types to be nullable (Int?, Float?, Double?), but doing so removes their primitive representation and causes them to be handled as boxed reference types. That boxing introduces extra allocations, indirection, and nullability checks that can quietly slow down performance-critical code such as tight loops or frequently called "hot" paths. The observable result is a loss of CPU-level optimizations available for raw primitives and potential GC or allocation overhead. To avoid this hidden cost, developers should prefer non-nullable primitives when possible, use primitive arrays or specialized collections, and profile code to detect boxing hotspots. Where nullability is required, consider design alternatives that minimize per-element boxing in performance-sensitive sections.
Kotlin 可空原始类型的隐藏成本
Int?、Float? 与 Double? 可能在不知不觉中拖慢你的关键路径性能。
重點摘要
可空原始类型会被装箱为引用类型
装箱带来额外分配、间接访问与 null 检查
在紧密循环与热路径中会明显降低性能
Kotlin 允许将原始数值类型设为可空(如 Int?、Float?、Double?),但这会使这些值失去原始表示并被装箱为引用类型。装箱会带来额外的内存分配、间接访问和空值检查,从而失去针对原始类型的 CPU 优化,在紧密循环或频繁调用的热路径中悄然降低性能。为避免这种隐性成本,应尽量使用非空原始类型、原生数组或专用集合,并通过性能分析找出装箱热点;在必须允许 null 的情况下,考虑设计替代方案以减少在性能敏感区域的逐元素装箱。
Kotlin 可為 Null 的原生型別的隱藏成本
Int?、Float? 與 Double? 可能在不知不覺中拖慢你效能關鍵的程式路徑。
重點摘要
可為 null 的原生型別會被包裝成參考型別
包裝導致額外配置、間接存取與 null 檢查
在緊密迴圈與熱路徑中會顯著影響效能
Kotlin 支援將原生數值型別設為可為 null(如 Int?、Float?、Double?),但這會讓這些值失去原生表示而被包裝為參考型別(boxing)。此包裝會帶來額外的記憶體配置、間接存取與 null 檢查,進而喪失原生型別的 CPU 優化,在緊密迴圈或頻繁呼叫的熱路徑中悄悄降低效能。為減少這類隱藏成本,應盡量使用不可為 null 的原生型別、原生陣列或專用集合,並透過效能剖析找出並最小化逐元素包裝的熱點;若必須允許 null,可考慮設計替代方案以避免在效能敏感區域產生大量 boxing。