Skip to content

Commit 25371c5

Browse files
authored
increase speed of Factorization objects
`searchsortedfirst` has much lower overhead than `first(searchsorted)`
1 parent 88d6227 commit 25371c5

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

src/factorization.jl

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,35 @@ Base.convert(::Type{Factorization}, d::AbstractDict) = Factorization(d)
1919
Base.iterate(f::Factorization, state...) = iterate(f.pe, state...)
2020

2121
function Base.get(f::Factorization, p, default)
22-
found = searchsorted(f.pe, p, by=first)
23-
isempty(found) ?
24-
default :
25-
last(f.pe[first(found)])
22+
found = searchsortedfirst(f.pe, p, by=first)
23+
(found > length(f.pe) || first(f.pe[found])) != p ? default : last(f.pe[found])
2624
end
2725

2826
Base.getindex(f::Factorization, p::Integer) = get(f, p, 0)
2927

3028
function Base.setindex!(f::Factorization{T}, e::Int, p::Integer) where T
31-
found = searchsorted(f.pe, p, by=first)
32-
if isempty(found)
33-
insert!(f.pe, first(found), T(p)=>e)
29+
found = searchsortedfirst(f.pe, p, by=first)
30+
if found > length(f.pe)
31+
push!(f.pe, T(p)=>e)
32+
elseif first(f.pe[found]) != p
33+
insert!(f.pe, found, T(p)=>e)
3434
else
35-
f.pe[first(found)] = T(p)=>e
35+
f.pe[found] = T(p)=>e
36+
end
37+
f
38+
end
39+
40+
"""
41+
impliments f[p] += e faster
42+
"""
43+
function increment!(f::Factorization{T}, e::Int, p::Integer) where T
44+
found = searchsortedfirst(f.pe, p, by=first)
45+
if found > length(f.pe)
46+
push!(f.pe, T(p)=>e)
47+
elseif first(f.pe[found]) != p
48+
insert!(f.pe, found, T(p)=>e)
49+
else
50+
f.pe[found] = T(p)=>(last(f.pe[found])+e)
3651
end
3752
f
3853
end

0 commit comments

Comments
 (0)