Skip to content

Commit

Permalink
Remove double allocations in Base.map by having to reverse the list
Browse files Browse the repository at this point in the history
instead create it recursively in-order, via tail-recursion

Big perf improvement:

Before:
```julia
julia> @Btime DataStructures.map(x->x*2, $(list((1:1000)...)));
  148.476 μs (6469 allocations: 163.55 KiB)
```
After:
```julia
julia> @Btime DataStructures.map(x->x*2, $(list((1:1000)...)));
  29.705 μs (1745 allocations: 42.89 KiB)
```
  • Loading branch information
NHDaly committed Oct 16, 2021
1 parent 214f3b3 commit fa11333
Showing 1 changed file with 2 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/list.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,8 @@ end
Base.map(f::Base.Callable, l::Nil) = l

function Base.map(f::Base.Callable, l::Cons{T}) where T
first = f(l.head)
l2 = cons(first, nil(typeof(first) <: T ? T : typeof(first)))
for h in l.tail
l2 = cons(f(h), l2)
end
reverse(l2)
rest = Base.map(f, l.tail)
return cons(f(l.head), rest)
end

function Base.filter(f::Function, l::LinkedList{T}) where T
Expand Down

0 comments on commit fa11333

Please sign in to comment.