Skip to content

Commit

Permalink
Merge pull request #188 from rafaqz/faster_collect_with_eltype
Browse files Browse the repository at this point in the history
less `push!` in collect_with_eltype
  • Loading branch information
SimonDanisch authored Jul 18, 2023
2 parents cb78c2a + 5ef5fb3 commit 09df8ea
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/geometry_primitives.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,32 @@ collect_with_eltype(::Type{T}, vec::Vector{T}) where {T} = vec
collect_with_eltype(::Type{T}, vec::AbstractVector{T}) where {T} = collect(vec)

function collect_with_eltype(::Type{T}, iter) where {T}
# TODO we could be super smart about allocating the right length
# but its kinda annoying, since e.g. T == Triangle and first(iter) isa Quad
# will need double the length etc - but could all be figured out ;)
result = T[]
# We need to get `eltype` information from `iter`, it seems to be `Any`
# most of the time so the eltype checks here don't actually work
l = if Base.IteratorSize(iter) isa Union{Base.HasShape,Base.HasLength}
if Base.IteratorEltype(iter) isa Base.HasEltype && isconcretetype(eltype(iter))
# Work out the exact length
length(convert_simplex(T, first(iter))) * length(iter)
else
# We know it is at least the length of iter,
# after that we will `push!` if we have to
length(iter)
end
else
0
end
n = 0
result = Vector{T}(undef, l)
for element in iter
# convert_simplex always returns a tuple,
# so that e.g. convert(Triangle, quad) can return 2 elements
for telement in convert_simplex(T, element)
push!(result, telement)
n += 1
if n > l
push!(result, telement)
else
result[n] = telement
end
end
end
return result
Expand Down

0 comments on commit 09df8ea

Please sign in to comment.