Skip to content

Commit 71d6a54

Browse files
authored
Add is_zero_initialized trait for matrix types (#1929)
... and use it to optimize a few default methods for matrix types that are zero initialized.
1 parent 331ad9b commit 71d6a54

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

src/Matrix.jl

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,18 @@ base_ring_type(::Type{<:MatrixElem{T}}) where T <: NCRingElement = parent_type(T
2222

2323
base_ring(a::MatrixElem{T}) where {T <: NCRingElement} = a.base_ring::parent_type(T)
2424

25+
"""
26+
is_zero_initialized(T::Type{<:MatrixElem})
27+
is_zero_initialized(mat::T) where {T<:MatrixElem}
28+
29+
Specify whether the default-constructed matrices of type `T`, via the
30+
`T(R::Ring, ::UndefInitializerm r::Int, c::Int)` constructor, are
31+
zero-initialized. The default is `false`, and new matrix types should
32+
specialize this method to return `true` if suitable, to enable optimizations.
33+
"""
34+
is_zero_initialized(::Type{<:MatrixElem}) = false
35+
is_zero_initialized(::T) where {T<:MatrixElem} = is_zero_initialized(T)
36+
2537
function check_parent(a::MatrixElem, b::MatrixElem, throw::Bool = true)
2638
fl = (base_ring(a) != base_ring(b) || nrows(a) != nrows(b) || ncols(a) != ncols(b))
2739
fl && throw && error("Incompatible matrix spaces in matrix operation")
@@ -374,8 +386,16 @@ with defaults based upon the given source matrix `x`.
374386
"""
375387
zero(x::MatElem{T}, R::NCRing) where T <: NCRingElement = zero(x, R, nrows(x), ncols(x))
376388
zero(x::MatElem{T}) where T <: NCRingElement = zero(x, nrows(x), ncols(x))
377-
zero(x::MatElem{T}, R::NCRing, r::Int, c::Int) where T <: NCRingElement = zero!(similar(x, R, r, c))
378-
zero(x::MatElem{T}, r::Int, c::Int) where T <: NCRingElement = zero!(similar(x, r, c))
389+
390+
function zero(x::MatElem{T}, R::NCRing, r::Int, c::Int) where T <: NCRingElement
391+
y = similar(x, R, r, c)
392+
return is_zero_initialized(y) ? y : zero!(y)
393+
end
394+
395+
function zero(x::MatElem{T}, r::Int, c::Int) where T <: NCRingElement
396+
y = similar(x, r, c)
397+
return is_zero_initialized(y) ? y : zero!(y)
398+
end
379399

380400
###############################################################################
381401
#
@@ -6769,7 +6789,8 @@ Return the $r \times c$ zero matrix over $R$.
67696789
"""
67706790
function zero_matrix(R::NCRing, r::Int, c::Int)
67716791
(r < 0 || c < 0) && error("Dimensions must be non-negative")
6772-
return zero!(dense_matrix_type(R)(R, undef, r, c))
6792+
mat = dense_matrix_type(R)(R, undef, r, c)
6793+
return is_zero_initialized(mat) ? mat : zero!(mat)
67736794
end
67746795

67756796
zero_matrix(::Type{MatElem}, R::Ring, n::Int, m::Int) = zero_matrix(R, n, m)

0 commit comments

Comments
 (0)