]> git.kaiwu.me - njs.git/commitdiff
Optimized nxt_dec_count() using bisection.
authorValentin Bartenev <vbart@nginx.com>
Thu, 25 Jul 2019 19:07:57 +0000 (22:07 +0300)
committerValentin Bartenev <vbart@nginx.com>
Thu, 25 Jul 2019 19:07:57 +0000 (22:07 +0300)
Previously, the number of comparisons required to count decimal numbers
was equal to decimal numbers count.

Now only 3 comparsions are needed for numbers with 1, 2, 3, 4, 5, or 6
decimal digits, and 4 comparsions are needed for numbers with 7, 8, 9,
and 10 decimal digits.

nxt/nxt_dtoa.c

index e9f1f331fc9130ac32e2cf393e13dacab061ae67..ebf74e56b1def984eb9b24654e2a316a0acb7c0b 100644 (file)
@@ -61,17 +61,27 @@ nxt_grisu2_round(char *start, size_t len, uint64_t delta, uint64_t rest,
 nxt_inline int
 nxt_dec_count(uint32_t n)
 {
-    if (n < 10) return 1;
-    if (n < 100) return 2;
-    if (n < 1000) return 3;
-    if (n < 10000) return 4;
-    if (n < 100000) return 5;
-    if (n < 1000000) return 6;
-    if (n < 10000000) return 7;
-    if (n < 100000000) return 8;
-    if (n < 1000000000) return 9;
-
-    return 10;
+    if (n < 10000) {
+        if (n < 100) {
+            return (n < 10) ? 1 : 2;
+
+        } else {
+            return (n < 1000) ? 3 : 4;
+        }
+
+    } else {
+        if (n < 1000000) {
+            return (n < 100000) ? 5 : 6;
+
+        } else {
+            if (n < 100000000) {
+                return (n < 10000000) ? 7 : 8;
+
+            } else {
+                return (n < 1000000000) ? 9 : 10;
+            }
+        }
+    }
 }