From 85aecaf79b2fc032d06c44e4cd3752d07c8b9434 Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Sat, 8 Mar 2025 19:23:11 +0700 Subject: [PATCH] Cache toInt() and toLong() results in Decimal$Regular --- .../dbotthepony/mc/otm/core/math/Decimal.kt | 40 +++++++++++++------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/ru/dbotthepony/mc/otm/core/math/Decimal.kt b/src/main/kotlin/ru/dbotthepony/mc/otm/core/math/Decimal.kt index 457874d17..4c4289757 100644 --- a/src/main/kotlin/ru/dbotthepony/mc/otm/core/math/Decimal.kt +++ b/src/main/kotlin/ru/dbotthepony/mc/otm/core/math/Decimal.kt @@ -240,24 +240,40 @@ sealed class Decimal : Number(), Comparable { return mag.signum() } + private var intCache = 0 + private var intComputed = false + override fun toInt(): Int { - return if (whole > BI_INT_MAX) { - Int.MAX_VALUE - } else if (whole < BI_INT_MIN) { - Int.MIN_VALUE - } else { - whole.toInt() + if (!intComputed) { + intCache = if (whole > BI_INT_MAX) { + Int.MAX_VALUE + } else if (whole < BI_INT_MIN) { + Int.MIN_VALUE + } else { + whole.toInt() + } + + intComputed = true } + + return intCache } + private var longCache = 0L + private var longComputed = false + override fun toLong(): Long { - return if (whole > BI_LONG_MAX) { - Long.MAX_VALUE - } else if (whole < BI_LONG_MIN) { - Long.MIN_VALUE - } else { - whole.toLong() + if (!longComputed) { + longCache = if (whole > BI_LONG_MAX) { + Long.MAX_VALUE + } else if (whole < BI_LONG_MIN) { + Long.MIN_VALUE + } else { + whole.toLong() + } } + + return longCache } override fun compareTo(other: Decimal): Int {