From 6051f868ce6b7b38b617d7f14f14f1b2a2f278a6 Mon Sep 17 00:00:00 2001 From: Giver Date: Wed, 30 Oct 2024 15:53:55 +0800 Subject: [PATCH] Improve pseudoRandom performance with bitwise operation Currently, pseudoRandom calculation uses the mod operator, which turns into fmod in the end. On non-x86 platforms, there's no hardware accelerated fmod operation, which leads to a high CPU loading and bottleneck under the software fmod calculations. Since the divisor RANDOM_RANGE is a power of 2, it can be replaced by bitwise operation, which can improve the performance a lot on non-x86 platforms and make the workload and performance more aligned among all platforms. It can also slightly improve the performance on x86 platforms. --- tdl/math.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tdl/math.js b/tdl/math.js index 561fdf23..78bf94b8 100644 --- a/tdl/math.js +++ b/tdl/math.js @@ -200,9 +200,9 @@ tdl.math.Matrix = goog.typedef; */ tdl.math.pseudoRandom = function() { var math = tdl.math; - return (math.randomSeed_ = - (134775813 * math.randomSeed_ + 1) % - math.RANDOM_RANGE_) / math.RANDOM_RANGE_; + math.randomSeed_ = (134775813 * math.randomSeed_ + 1) & (math.RANDOM_RANGE_ - 1); + math.randomSeed_ += (math.randomSeed_ < 0) * math.RANDOM_RANGE_; + return math.randomSeed_ / math.RANDOM_RANGE_; }; /**