I wish to combine two arrays, lets say a = [1, 2, 3, …] and b = [4, 5, 6, …], so that the elements alternate between them like so: c = [1, 4, 2, 5, 3, 6, …]. My first attempt was to make an “my_combine” object like so:
julia> using Base
julia> struct my_combine{T <: Tuple} <: AbstractArray{eltype(T), 1}
_x::T
_size::Int
my_combine(args...) = new{typeof(args)}(args, sum(length(i) for i in args))
end
julia> Base.getindex(a::my_combine, i::Int) = a._x[(i-1)%length(a._x)+1][div(i-1, length(a._x))+1]
julia> Base.size(a::my_combine) = (a._size,)
Which gives the desired effect. But, when benchmarked, its seems to be a bit slow when compared to other combining functions like zip:
julia> r1 = rand(1000); r2 = rand(1000);
julia> @time for a in my_combine(r1, r2)
a
end
0.000117 seconds (4.00 k allocations: 125.109 KiB)
“my_combine” seems to be twice as slow, and takes up twice the memory, as zip:
julia> @time for (a,b) in zip(r1, r2)
(a,b)
end
0.000053 seconds (2.00 k allocations: 78.156 KiB)
I’m still a bit new to Julia, so I’m sure I’m missing some performance tricks. Any thoughts?