Skip to content

Commit

Permalink
Merge pull request #301 from glureau/perf_bigdecimal_zero_comparison
Browse files Browse the repository at this point in the history
BigDecimal: Replace ==ZERO by isZero, ~40% time reduction on main methods
  • Loading branch information
ionspin committed Jul 14, 2024
2 parents e32ae81 + 418fc12 commit 952c28a
Showing 1 changed file with 8 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1096,10 +1096,10 @@ class BigDecimal private constructor(
*/
fun add(other: BigDecimal, decimalMode: DecimalMode? = null): BigDecimal {
val resolvedDecimalMode = resolveDecimalMode(this.decimalMode, other.decimalMode, decimalMode)
if (this == ZERO) {
if (this.isZero()) {
return roundOrDont(other.significand, other.exponent, resolvedDecimalMode)
}
if (other == ZERO) {
if (other.isZero()) {
return roundOrDont(this.significand, this.exponent, resolvedDecimalMode)
}
val (first, second, _) = bringSignificandToSameExponent(this, other)
Expand Down Expand Up @@ -1153,10 +1153,10 @@ class BigDecimal private constructor(
fun subtract(other: BigDecimal, decimalMode: DecimalMode? = null): BigDecimal {
val resolvedDecimalMode = resolveDecimalMode(this.decimalMode, other.decimalMode, decimalMode)

if (this == ZERO) {
if (this.isZero()) {
return roundOrDont(other.significand.negate(), other.exponent, resolvedDecimalMode)
}
if (other == ZERO) {
if (other.isZero()) {
return roundOrDont(this.significand, this.exponent, resolvedDecimalMode)
}

Expand Down Expand Up @@ -1514,7 +1514,7 @@ class BigDecimal private constructor(
* the same number i.e. 1.234
*/
private fun removeTrailingZeroes(bigDecimal: BigDecimal): BigDecimal {
if (bigDecimal == ZERO) return this
if (bigDecimal.isZero()) return this
var significand = bigDecimal.significand
var divisionResult = BigInteger.QuotientAndRemainder(bigDecimal.significand, BigInteger.ZERO)
do {
Expand Down Expand Up @@ -1657,7 +1657,7 @@ class BigDecimal private constructor(
* as division.
*/
override fun pow(exponent: Long): BigDecimal {
if (this == ZERO && exponent < 0) {
if (this.isZero() && exponent < 0) {
throw ArithmeticException("Negative exponentiation of zero is not defined.")
}
var result = this
Expand Down Expand Up @@ -2167,7 +2167,7 @@ class BigDecimal private constructor(
}

override fun hashCode(): Int {
if (this == ZERO) {
if (this.isZero()) {
return 0
}
return removeTrailingZeroes(this).significand.hashCode() + exponent.hashCode()
Expand Down Expand Up @@ -2253,7 +2253,7 @@ class BigDecimal private constructor(
* i.e. 123000000 for 1.23E+9 or 0.00000000123 for 1.23E-9
*/
fun toStringExpanded(): String {
if (this == ZERO) {
if (this.isZero()) {
return "0"
}
val digits = significand.numberOfDecimalDigits()
Expand Down

0 comments on commit 952c28a

Please sign in to comment.