What's the point of static arrays ?
Simen Kjærås
simen.kjaras at gmail.com
Thu Jul 9 12:48:26 UTC 2020
On Thursday, 9 July 2020 at 12:12:06 UTC, wjoe wrote:
> I'm not considering supposed performance benefits/penalties
> because these need to be profiled.
>
> Considering the many downsides why would I ever want to choose
> a static over a dynamic array ?
Simply put: static arrays are not dynamic arrays, and if you try
to use one as the other you're going to be disappointed.
Usually, you use static arrays when you interface with something
else that does it - generally a file format or a C library. For
the most part you're right, you should probably use a dynamic
array instead.
Now, as for your points:
> - Can neither grow nor shrink them
> - Can't append elements
> - Can't remove elements
These are the same as the first point.
> - Can't slice them
> - Can't range them
Sure you can:
unittest {
import std.stdio;
import std.algorithm;
int[10] a = [1,2,3,4,5,6,7,8,9,10];
// Note I'm slicing the static array to use in range
algorithms:
writeln(a[].map!(b => b+2));
// Slicing works:
auto b = a[3..6];
b[] = 7;
writeln(a);
}
> - Assignment copies the whole array, as in int[5] a; auto b = a;
This is often a factor in choosing a static array. It's not
better or worse, just different. And sometimes it's different in
exactly the way you need.
> - Size is limited by stack
> - Stack overflow issues
So allocate your static array on the heap if this is a problem?
> Some of the cons could be considered a feature.
> Also GC but it's possible to make a dynamic array
> implementation which avoids the GC.
Basically none of the drawbacks you refer to are actual
drawbacks, but instead part of what makes static arrays useful.
Static arrays are not a poor man's dynamic arrays, they're a
different beast, doing different things.
--
Simen
More information about the Digitalmars-d-learn
mailing list