
- Lighter, as every object adds additional weight.
- Faster, as accessing a value through accessors is an additional cost, and creating an object is also a cost.
List or Set are generic. Primitives cannot be used as generic types, so we end up using wrapped types instead. This is a convenient solution that suits most cases as it is easier to do processing over standard collections. Having said that, in performance-critical parts of our code we should instead consider using arrays with primitives, like IntArray or LongArray, as they are lighter in terms of memory and their processing is more efficient.|-------------|---------------|
| Int | int |
| List<Int> | List<Integer> |
| Array<Int> | Integer[] |
| IntArray | int[] |
IntArray or in List<Int>. If you make some measurements, you will find that on a typical machine IntArray allocates 4,000,016 bytes, while List<Int> allocates 20,000,040 bytes, which is 5 times more. If it is possible to optimize for memory use, choose arrays with primitives.import jdk.nashorn.internal.ir.debug.ObjectSizeCalculator .getObjectSize fun main() { val ints = List(1_000_000) { it } val array: Array<Int> = ints.toTypedArray() val intArray: IntArray = ints.toIntArray() println(getObjectSize(ints)) // 20 000 040 println(getObjectSize(array)) // 20 000 016 println(getObjectSize(intArray)) // 4 000 016 }
open class InlineFilterBenchmark { lateinit var list: List<Int> lateinit var array: IntArray @Setup fun init() { list = List(1_000_000) { it } array = IntArray(1_000_000) { it } } @Benchmark // On average 1 260 593 ns fun averageOnIntList(): Double { return list.average() } @Benchmark // On average 868 509 ns fun averageOnIntArray(): Double { return array.average() } }
List or Set should be preferred over arrays. However, if you hold big collections of values that can be represented as primitives, using arrays of primitives might significantly improve your performance and memory use. This is especially important for library creators or developers who write games or do advanced graphic processing.