Skip to content

Commit f8bff3d

Browse files
authored
remove allocations in transpose! by specializing on function argument (#157)
1 parent 7745517 commit f8bff3d

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/sparsematrix.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1088,7 +1088,7 @@ algorithms for sparse matrices: multiplication and permuted transposition," ACM
10881088
beyond that passed in.
10891089
"""
10901090
function halfperm!(X::AbstractSparseMatrixCSC{Tv,Ti}, A::AbstractSparseMatrixCSC{TvA,Ti},
1091-
q::AbstractVector{<:Integer}, f::Function = identity) where {Tv,TvA,Ti}
1091+
q::AbstractVector{<:Integer}, f::F = identity) where {Tv,TvA,Ti,F<:Function}
10921092
_computecolptrs_halfperm!(X, A)
10931093
_distributevals_halfperm!(X, A, q, f)
10941094
return X
@@ -1119,7 +1119,7 @@ distributing `rowvals(A)` and `f`-transformed `nonzeros(A)` into `rowvals(X)` an
11191119
respectively. Simultaneously fixes the one-position-forward shift in `getcolptr(X)`.
11201120
"""
11211121
@noinline function _distributevals_halfperm!(X::AbstractSparseMatrixCSC{Tv,Ti},
1122-
A::AbstractSparseMatrixCSC{TvA,Ti}, q::AbstractVector{<:Integer}, f::Function) where {Tv,TvA,Ti}
1122+
A::AbstractSparseMatrixCSC{TvA,Ti}, q::AbstractVector{<:Integer}, f::F) where {Tv,TvA,Ti,F<:Function}
11231123
resize!(nonzeros(X), nnz(A))
11241124
resize!(rowvals(X), nnz(A))
11251125
@inbounds for Xi in 1:size(A, 2)
@@ -1143,7 +1143,7 @@ No additonal memory is allocated other than resizing the rowval and nzval of `X`
11431143
11441144
See `halfperm!`
11451145
"""
1146-
function ftranspose!(X::AbstractSparseMatrixCSC{Tv,Ti}, A::AbstractSparseMatrixCSC{Tv,Ti}, f::Function) where {Tv,Ti}
1146+
function ftranspose!(X::AbstractSparseMatrixCSC{Tv,Ti}, A::AbstractSparseMatrixCSC{Tv,Ti}, f::F) where {Tv,Ti,F<:Function}
11471147
# Check compatibility of source argument A and destination argument X
11481148
if size(X, 2) != size(A, 1)
11491149
throw(DimensionMismatch(string("destination argument `X`'s column count, ",

test/sparsematrix_ops.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,4 +442,15 @@ end
442442
@test one(A) isa SparseMatrixCSC{Int}
443443
end
444444

445+
@testset "transpose! does not allocate" begin
446+
function f()
447+
A = sprandn(10, 10, 0.1)
448+
X = copy(A)
449+
return @allocated transpose!(X, A)
450+
end
451+
#precompile
452+
f()
453+
f()
454+
@test f() == 0
455+
end
445456
end # module

0 commit comments

Comments
 (0)