# Efficiency of push! on a Vector vs push on an SVector

**URL:** <https://discourse.julialang.org/t/efficiency-of-push-on-a-vector-vs-push-on-an-svector/63313>\
**Category:** General Usage\
**Tags:** question, performance\
**Created:** [June 21, 2021, 4:29pm UTC](https://discourse.julialang.org/t/efficiency-of-push-on-a-vector-vs-push-on-an-svector/63313 "2021-06-21T16:29:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)\
**Post date:** [June 21, 2021, 4:29pm UTC](https://discourse.julialang.org/t/efficiency-of-push-on-a-vector-vs-push-on-an-svector/63313/1 "2021-06-21T16:29:49Z")

</div>

Are there cases where it might be more efficient to use `push` with an `SVector` than to use `push!` with a `Vector`?

I have one benchmark below where `push!` is much more efficient:

```julia
using StaticArrays
using BenchmarkTools

function foo(x)
    y = SVector{0, eltype(x)}()
    for v in x
        y = push(y, v)
    end
    y
end

function bar(x)
    y = Vector{eltype(x)}()
    for v in x
        push!(y, v)
    end
    y
end

x = 1:50

```

```julia
julia> @btime foo($x);
  5.740 μs (50 allocations: 10.67 KiB)

julia> @btime bar($x);
  410.457 ns (6 allocations: 1.14 KiB)

```

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [June 21, 2021, 5:04pm UTC](https://discourse.julialang.org/t/efficiency-of-push-on-a-vector-vs-push-on-an-svector/63313/2 "2021-06-21T17:04:35Z")

</div>

> [@CameronBieganek](#):
>
> Are there cases where it might be more efficient to use `push` with an `SVector` than to use `push!` with a `Vector` ?

`SVector` is only efficient when the length of the vector is known at compile time, because the length is a part of the type. If you have a runtime `push!` loop, where the compiler doesn’t know the number of loop iterations, using `SVector` will be type-unstable and hence slow.

(The reason why something like `SVector` is not the default array type in Julia is that they are much less versatile than `Array` … but for the specialized cases where `SVector` applies, they are fantastic.)
