stream: micro-optimize high water mark calculation
authorBen Noordhuis <info@bnoordhuis.nl>
Thu, 20 Aug 2015 20:29:57 +0000 (22:29 +0200)
committerBen Noordhuis <info@bnoordhuis.nl>
Mon, 24 Aug 2015 18:24:13 +0000 (20:24 +0200)
Don't iterate over all 32 bits, use some hacker's delight bit twiddling
to compute the next power of two.

The logic can be reduced to `n = 1 << 32 - Math.clz32(n)` but then it
can't easily be backported to v2.x; Math.clz32() was added in V8 4.3.

PR-URL: https://github.com/nodejs/node/pull/2479
Reviewed-By: Chris Dickinson <christopher.s.dickinson@gmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
lib/_stream_readable.js

index 644c4ff..766577a 100644 (file)
@@ -198,7 +198,11 @@ function roundUpToNextPowerOf2(n) {
   } else {
     // Get the next highest power of 2
     n--;
-    for (var p = 1; p < 32; p <<= 1) n |= n >> p;
+    n |= n >>> 1;
+    n |= n >>> 2;
+    n |= n >>> 4;
+    n |= n >>> 8;
+    n |= n >>> 16;
     n++;
   }
   return n;