https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ayfri

06/01/2022, 10:51 AM
Hi, in which cases should I use arrays instead of lists ?
e

elect

06/01/2022, 10:59 AM
performance, but we are talking about special corner cases
r

Robert Williams

06/01/2022, 11:03 AM
Pretty much just interop with legacy APIs that require Arrays (very common in Java APIs)
Generally you don't want to be building new kotlin APIs that force you to use Arrays
Except ByteArray, that's still pretty common for performance
a

Ayfri

06/01/2022, 11:47 AM
Should I use them for DoubleArrays and IntArrays ?
r

Robert Williams

06/01/2022, 11:55 AM
Again, depends on the application, how large you expect them to be and how much performance matters. If it's something like ARGB pixel values for image processing an array might make sense (although that may also be enforced by interop if you're using an image processing library)
a

Ayfri

06/01/2022, 11:58 AM
Okay I see, thanks !
a

Adam Powell

06/01/2022, 2:06 PM
Working with primitives and arrays together happens often because usually if you're working with primitives instead of higher level data elements you're doing it for performance reasons in the first place
r

Ruckus

06/01/2022, 3:16 PM
The general rule I've always gone by is
If you don't know if you need an array, you don't need an array
I know it's rather self-fulfilling, but it's worked pretty well for me
😂 1
1
a

Ayfri

06/01/2022, 3:19 PM
For a game where I do some big calculations on coordinates or something and I store a lot of numbers in a list, should I use then an array ?
e

elect

06/01/2022, 3:21 PM
if the size is fixed and known a priori, you may use it
a

Ayfri

06/01/2022, 3:31 PM
Okay it's very specific I see
r

Ruckus

06/01/2022, 4:35 PM
For something like that, I would use an appropriate dedicated math library and the abstractions it provides. They tend to be quite well optimized.
If your goal is to just hold on to some data for a while, a list is probably a better option. It's useful to not think of arrays and lists as different implementations of the same data structure, but instead as fundamentally different data structures with different use cases.
5 Views