Avoiding Vectors of Abstract Types

I am far from understanding where “world splitting” happens in your example, but changing

function mysum(mv::Vector{T}) where T
    sum([v.x for v in mv])
end

to

function mysum(mv::Vector{T}) where T
	s=0
	for i=1:length(mv)
		s+=mv[i].x
	end
    return s
end

Results in much better timings:

  59.99385162601627  # 1
  62.53760935910483  # 2
 392.1048792270531   # 3 
 392.31189320388347  # 4 types in the union
 393.2404761904762   # 5
 391.7910280373831   # 7
 391.6691304347826   # 8

And I would also call the second version “acting on the data”.

1 Like

I was puzzled why union splitting doesn’t work here…

Following the Julia rule “if in doubt write your own loop” I rewrote mysum as

function mysum(mv)
    s=0
    for i=1:length(mv)
        s+=mv[i].x
    end
    s
end

and get (note the logscale of the y-axis):

In your function somewhere – may be in the array comprehension – Julia seems to fall back to “world splitting” instead of “union splitting”.

1 Like

But…

function mysum(mv)
    s=0
    for v ∈ mv
        s+=v.x
    end
    s
end

and

function mysum(mv)
    s=0
    foreach(mv) do v
        s+=v.x
    end
    s
end