[njs] Optimized nxt_dec_count() using bisection.

Valentin Bartenev vbart at nginx.com
Thu Jul 25 21:24:50 UTC 2019


details:   https://hg.nginx.org/njs/rev/89082cb0bc84
branches:  
changeset: 1069:89082cb0bc84
user:      Valentin Bartenev <vbart at nginx.com>
date:      Thu Jul 25 22:07:57 2019 +0300
description:
Optimized nxt_dec_count() using bisection.

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.

diffstat:

 nxt/nxt_dtoa.c |  30 ++++++++++++++++++++----------
 1 files changed, 20 insertions(+), 10 deletions(-)

diffs (41 lines):

diff -r 644af379d226 -r 89082cb0bc84 nxt/nxt_dtoa.c
--- a/nxt/nxt_dtoa.c	Thu Jul 25 20:17:42 2019 +0300
+++ b/nxt/nxt_dtoa.c	Thu Jul 25 22:07:57 2019 +0300
@@ -61,17 +61,27 @@ nxt_grisu2_round(char *start, size_t len
 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;
+    if (n < 10000) {
+        if (n < 100) {
+            return (n < 10) ? 1 : 2;
+
+        } else {
+            return (n < 1000) ? 3 : 4;
+        }
 
-    return 10;
+    } else {
+        if (n < 1000000) {
+            return (n < 100000) ? 5 : 6;
+
+        } else {
+            if (n < 100000000) {
+                return (n < 10000000) ? 7 : 8;
+
+            } else {
+                return (n < 1000000000) ? 9 : 10;
+            }
+        }
+    }
 }
 
 


More information about the nginx-devel mailing list