Skip to content

Commit fa11333

Browse files
committed
Remove double allocations in Base.map by having to reverse the list
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) ```
1 parent 214f3b3 commit fa11333

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

src/list.jl

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,8 @@ end
7070
Base.map(f::Base.Callable, l::Nil) = l
7171

7272
function Base.map(f::Base.Callable, l::Cons{T}) where T
73-
first = f(l.head)
74-
l2 = cons(first, nil(typeof(first) <: T ? T : typeof(first)))
75-
for h in l.tail
76-
l2 = cons(f(h), l2)
77-
end
78-
reverse(l2)
73+
rest = Base.map(f, l.tail)
74+
return cons(f(l.head), rest)
7975
end
8076

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

0 commit comments

Comments
 (0)