Skip to content

Commit 5f449f5

Browse files
authored
Faster Adjoint/Transpose-UniformScaling arithmetic (#1366)
Avoids hitting slow generic methods. Discussed in https://discourse.julialang.org/t/very-long-time-for-addition-of-complex-identity-matrix-to-transposed-sparse-matrix/129465. After this, the following are comparable: ```julia julia> A = sprandn(90, 90, 0.01); julia> @Btime ($A + complex(0,1.) * I); 1.313 μs (13 allocations: 8.02 KiB) julia> @Btime (transpose($A) + complex(0,1.) * I); 1.416 μs (13 allocations: 8.02 KiB) ```
1 parent aabb06f commit 5f449f5

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/uniformscaling.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,17 @@ function (-)(J::UniformScaling{<:Complex}, A::Hermitian)
217217
return B
218218
end
219219

220+
function (+)(A::AdjOrTransAbsMat, J::UniformScaling)
221+
checksquare(A)
222+
op = wrapperop(A)
223+
op(op(A) + op(J))
224+
end
225+
function (-)(J::UniformScaling, A::AdjOrTransAbsMat)
226+
checksquare(A)
227+
op = wrapperop(A)
228+
op(op(J) - op(A))
229+
end
230+
220231
function (+)(A::AbstractMatrix, J::UniformScaling)
221232
checksquare(A)
222233
B = copymutable_oftype(A, Base.promote_op(+, eltype(A), typeof(J)))

test/uniformscaling.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,19 @@ let
335335
@test @inferred(J - T) == J - Array(T)
336336
end
337337

338+
@testset for f in (transpose, adjoint)
339+
if isa(A, Array)
340+
T = f(randn(ComplexF64,3,3))
341+
else
342+
T = f(view(randn(ComplexF64,3,3), 1:3, 1:3))
343+
end
344+
TA = Array(T)
345+
@test @inferred(T + J) == TA + J
346+
@test @inferred(J + T) == J + TA
347+
@test @inferred(T - J) == TA - J
348+
@test @inferred(J - T) == J - TA
349+
end
350+
338351
@test @inferred(I\A) == A
339352
@test @inferred(A\I) == inv(A)
340353
@test @inferred\I) === UniformScaling(1/λ)

0 commit comments

Comments
 (0)