# Functional implementation of collect

**URL:** <https://discourse.julialang.org/t/functional-implementation-of-collect/15177>\
**Category:** General Usage\
**Tags:** question\
**Created:** [September 19, 2018, 2:32pm UTC](https://discourse.julialang.org/t/functional-implementation-of-collect/15177 "2018-09-19T14:32:38Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 20, 2018, 8:11am UTC](https://discourse.julialang.org/t/functional-implementation-of-collect/15177/2 "2018-09-20T08:11:56Z")

</div>

It seems that simply testing if a new collection was allocated with `isequal` generates super-efficient code, eg

```julia
# "functional" implementation take 2
store!_or_widen(collection::Vector{T}, elt::S) where {T, S <: T} = push!(collection, elt)
store!_or_widen(collection, elt) = vcat(collection, elt)

function mycollect_funeq(itr)
    y = iterate(itr)
    y ≡ nothing && error("not allowed")
    elt, state = y
    _mycollect_funeq([elt], itr, state)
end

function _mycollect_funeq(collection, itr, state)
    while true
        y = iterate(itr, state)
        y ≡ nothing && return collection
        elt, state = y
        expanded = store!_or_widen(collection, elt)
        expanded ≡ collection || return _mycollect_funeq(expanded, itr, state)
    end
end

```

benchmarks as

```julia
julia> @btime collect($itr);
  60.238 μs (14 allocations: 30.94 KiB)

julia> @btime mycollect_fun($itr);
  37.332 μs (1520 allocations: 70.88 KiB)

julia> @btime mycollect_mut($itr);
  41.366 μs (990 allocations: 46.30 KiB)

julia> @btime mycollect_funeq($itr); # this is the new one
  28.801 μs (520 allocations: 39.64 KiB)

```

 ![bitmap](https://global.discourse-cdn.com/julialang/original/3X/e/2/e2500ecd78174e883ecc967b1fb0c981895cd7c1.png)

---

_[View the full topic](https://discourse.julialang.org/t/functional-implementation-of-collect/15177)._
