Is there a faster/more elegant way to constructing the following:

```
X = [zeros(2) for i=1:10]
```

to get an array of 2D vectors? Also, how important for performance is it to preallocate such arrays, as opposed to concatenating them?

Is there a faster/more elegant way to constructing the following:

```
X = [zeros(2) for i=1:10]
```

to get an array of 2D vectors? Also, how important for performance is it to preallocate such arrays, as opposed to concatenating them?

That does not create an array of “2D” vectors (it creates an array/vector of vectors/1D arrays) and it does not concatenate anything. If you actually want exactly what `X`

is than it’s about the best way to do it. If you want something else, you should specify exactly what you want, e.g. 2D array with `zeros(2, 10)`

. Finally how important for performance something is not a question possible to answer, or the answer is always, depend on how important it is to you.

Got it. Yes, I want what the above code actually produces. I’ll stick with that, then.

What about `[@SVector zeros(2) for i in 1:10]`

? then the internal arrays can be stack allocated and do other things well. If you know they are all going to be small, this can be fast.

3 Likes

Note also that `@SVector`

is from StaticArrays.jl.

1 Like

Or SVector(0.0, 0.0) which is both shorter and more explicit?