Kotlin中Array<Double>与DoubleArray的区别及JNI场景选型疑问
Core Differences Between
Array<Double> and DoubleArray in Kotlin, Plus JNI Context Great question—this is a common point of confusion, especially when working with JNI where the distinction hits close to home. Let’s break this down clearly:
Key Core Differences
Underlying Storage Type
val array: Array<Double>is an array of boxedDoubleobjects. Each element is a full Java/Kotlin object stored on the heap, complete with an object header (metadata like hash code, GC flags, etc.).val array: DoubleArrayis an array of primitivedoublevalues. It maps directly to Java’sdouble[], which is a contiguous block of raw memory holding 8-byte floating-point numbers with no object overhead.
Memory Efficiency
Array<Double>wastes a lot of memory: eachDoubleobject takes ~24 bytes (16-byte object header + 8-bytedoublevalue) on most JVMs, compared to just 8 bytes per element inDoubleArray. For large arrays, this adds up drastically.
Nullability
Array<Double>allowsnullvalues (since it holds objects), which can be useful if you need to represent missing data.DoubleArraycannot holdnull—all elements default to0.0, as primitive types don’t support nullability.
Performance: Is DoubleArray Worse?
Absolutely not—DoubleArray is far more performant than Array<Double>:
- No boxing/unboxing overhead: Every time you read or write an element in
Array<Double>, the JVM has to convert between theDoubleobject and the primitivedouble(boxing when storing, unboxing when retrieving).DoubleArrayskips this entirely. - Better cache locality: Since
DoubleArrayuses contiguous raw memory, CPU caches can fetch chunks of the array more efficiently, making loops and bulk operations much faster.
The only "disadvantage" of DoubleArray is the lack of null support—but that’s a deliberate tradeoff for performance and memory efficiency.
JNI Context: Why This Matters For You
Your JNI code highlights exactly why DoubleArray is the better choice here:
- Working with
Array<Double>(which maps to Java’sDouble[]) requires you to manually createDoubleobjects via constructors, as you noted withFindClass("java/lang/Double")andGetMethodID("<init>"). This adds significant overhead: each object creation involves JNI calls, heap allocation, and constructor execution. DoubleArraymaps directly to Java’sdouble[], which JNI supports natively. You can use functions likeGetDoubleArrayElements()to get a direct pointer to the rawdoublevalues in memory, modify them directly, and then callReleaseDoubleArrayElements()to sync back. This skips all the object-related hassle and is vastly more efficient.
So if you don’t need to store null values, always prefer DoubleArray—it’s faster, uses less memory, and makes your JNI code simpler and more performant.
内容的提问来源于stack exchange,提问作者Martin Perry
相关产品推荐
相关产品推荐

