But what if you do have a very small number of elements? Let's say I am
working with 2D or 3D points and wonder whether to represent them as
vectors, tuples or a custom type, like
immutable Point2D{T<:Real}
x::T
y::T
end
Base.(:+){T}(p1::Point2D{T}, p2::Point2D{T}) = Point2D(p1.x+p2.x, p1.y+p2.y)
I tried a test here (running it multiple times of course):
function time_2D(N)
a, b = randn(2), randn(2)
at, bt = (randn(2)...), (randn(2)...)
p1, p2 = Point2D(randn(2)...), Point2D(randn(2)...)
@time for _ in 1:N c = a + b end
@time for _ in 1:N ct = (at[1]+bt[1], at[2]+bt[2]) end
@time for _ in 1:N p = p1 + p2 end
end
>> time_2D(10^7)
0.672306 seconds (20.00 M allocations: 915.527 MB, 16.94% gc time)
0.784473 seconds (40.00 M allocations: 610.352 MB, 9.68% gc time)
0.336439 seconds (10.00 M allocations: 305.176 MB, 15.36% gc time)
which seems to indicate that tuples are not so fast, but the custom type is
quite fast. But it's hard to know whether simple benchmarks like these are
representative, maybe the compiler is optimizing away stuff, and so on.
Are there any general tips or guidelines for how to choose between vectors,
tuples and composite types'? The existence of FixedSizeArrays.jl
<https://github.com/SimonDanisch/FixedSizeArrays.jl> seems to point to
structs/composite types as being optimal. Would that be a correct
impression?
On Monday, April 11, 2016 at 11:33:15 PM UTC+2, Yichao Yu wrote:
>
> On Mon, Apr 11, 2016 at 4:00 PM, Anonymous <[email protected] <javascript:>>
> wrote:
> > If I have a vector of data which I don't intend to ever change, should I
> > represent it as a tuple rather than a 1d array? Is there any benefit
> above
> > and beyond protecting against mutability? Is it more efficient?
>
> Unless you only have a very small number of element, (maybe ~10), you
> should just use an array.
>