Nim: advantage of using array over seq?
Asked Answered
T

1

6

From the docs, I know that Nim arrays have a fixed length determined at compile time, whereas seqs have a variable length.

I notice that seqs have more builtin tools. For example, in the sequtils module, map can take an array but will return a seq anyway, and all or any do not work with arrays. And I don't see an easy way to convert a fixed-size seq into an array.

So my question is: what are the benefits of using arrays? Do they provide faster access?

Televisor answered 10/12, 2017 at 13:50 Comment(0)
H
11

A Nim seq is in fact a pointer to a dynamic array (which consists of two words for the seq's length and capacity, plus the actual data).

A seq requires another level of indirection, an additional heap allocation, and has additional overhead (the memory needed to store length and capacity, plus any "wasted" memory that is not currently being used). So, if you know exactly how much memory you need, you can save both time and space by using an array instead of a seq.

Hax answered 10/12, 2017 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.