Cache toInt() and toLong() results in Decimal$Regular

This commit is contained in:
DBotThePony 2025-03-08 19:23:11 +07:00
parent 65d076f634
commit 85aecaf79b
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -240,18 +240,31 @@ sealed class Decimal : Number(), Comparable<Decimal> {
return mag.signum() return mag.signum()
} }
private var intCache = 0
private var intComputed = false
override fun toInt(): Int { override fun toInt(): Int {
return if (whole > BI_INT_MAX) { if (!intComputed) {
intCache = if (whole > BI_INT_MAX) {
Int.MAX_VALUE Int.MAX_VALUE
} else if (whole < BI_INT_MIN) { } else if (whole < BI_INT_MIN) {
Int.MIN_VALUE Int.MIN_VALUE
} else { } else {
whole.toInt() whole.toInt()
} }
intComputed = true
} }
return intCache
}
private var longCache = 0L
private var longComputed = false
override fun toLong(): Long { override fun toLong(): Long {
return if (whole > BI_LONG_MAX) { if (!longComputed) {
longCache = if (whole > BI_LONG_MAX) {
Long.MAX_VALUE Long.MAX_VALUE
} else if (whole < BI_LONG_MIN) { } else if (whole < BI_LONG_MIN) {
Long.MIN_VALUE Long.MIN_VALUE
@ -260,6 +273,9 @@ sealed class Decimal : Number(), Comparable<Decimal> {
} }
} }
return longCache
}
override fun compareTo(other: Decimal): Int { override fun compareTo(other: Decimal): Int {
return if (other === Zero) return if (other === Zero)
signum() signum()