Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

speed up filter of vector #31929

Merged
merged 12 commits into from
Jul 5, 2019
23 changes: 22 additions & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2364,7 +2364,28 @@ function filter!(f, a::AbstractVector)
return a
end

filter(f, a::Vector) = mapfilter(f, push!, a, empty(a))
function filter!(f, a::Vector)
j = 1
for ai in a
@inbounds a[j] = ai
j = ifelse(f(ai), j+1, j)
chethega marked this conversation as resolved.
Show resolved Hide resolved
end
deleteat!(a, j:length(a))
sizehint!(a, length(a))
a
end

function filter(f, a::AbstractVector{T}) where T
j = 1
chethega marked this conversation as resolved.
Show resolved Hide resolved
b = Vector{T}(undef, length(a))
for ai in a
@inbounds b[j] = ai
j = ifelse(f(ai), j+1, j)
end
deleteat!(b, j:length(b))
sizehint!(b, length(b))
b
end

# set-like operators for vectors
# These are moderately efficient, preserve order, and remove dupes.
Expand Down