Skip to content

Commit 1768c58

Browse files
NHDalyomus
authored andcommitted
Performance fix: avoid unnecessary convert on setindex!、copy when type is same. (#38)
* Add `convert(::Type{T}, x::T) where {T<:FD} = x` This fixes unnecessary copies on `setindex!`, etc. * Remove "copy constructor" after correct `convert` fix The "copy constructor" is no longer necessary now that a no-op `convert` is added, since by default construction falls back to convert. To verify, after this change, the performance is still correct: ``` julia> f = FixedPointDecimals.FixedDecimal{Int128,2}(3.25) FixedDecimal{Int128,2}(3.25) julia> @Btime x = FixedPointDecimals.FixedDecimal{Int128, 2}($f) 0.036 ns (0 allocations: 0 bytes) FixedDecimal{Int128,2}(3.25) ``` And `@code_native` shows this to be a simple reinterpret.
1 parent d87debb commit 1768c58

File tree

1 file changed

+2
-3
lines changed

1 file changed

+2
-3
lines changed

src/FixedPointDecimals.jl

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,6 @@ struct FixedDecimal{T <: Integer, f} <: Real
9999
_throw_storage_error(f, T, n)
100100
end
101101
end
102-
103-
# Copy constructor -- prevents unneeded work to convert between the same types
104-
FixedDecimal{T,f}(x::FixedDecimal{T,f}) where {T<:Integer,f} = new{T,f}(x.i)
105102
end
106103

107104
@noinline function _throw_storage_error(f, T, n)
@@ -274,6 +271,8 @@ function round(::Type{FD{T, f}}, x::Rational, ::RoundingMode{:Nearest}=RoundNear
274271
end
275272

276273
# conversions and promotions
274+
convert(::Type{FD{T, f}}, x::FD{T, f}) where {T, f} = x # Converting an FD to itself is a no-op
275+
277276
function convert(::Type{FD{T, f}}, x::Integer) where {T, f}
278277
reinterpret(FD{T, f}, T(widemul(x, coefficient(FD{T, f}))))
279278
end

0 commit comments

Comments
 (0)