Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active May 13, 2021 09:09
Show Gist options
  • Save JamieMason/1922577 to your computer and use it in GitHub Desktop.
Save JamieMason/1922577 to your computer and use it in GitHub Desktop.
JavaScript Duff's Device
/**
* 1. Original JS Implementation by Jeff Greenberg 2/2001 - http://home.earthlink.net/~kendrasg/info/js_opt/
* 2. (fast duff's device) from an anonymous donor to Jeff Greenberg's site
* 3. (faster duff's defice) by Andrew King 8/2002 for WebSiteOptimization.com
* 4. bug fix (for iterations<8) by Andrew B. King April 12, 2003
*/
function duffsDevice (iterations) {
var testVal = 0,
n = iterations % 8;
if (n > 0) {
do {
testVal++;
}
while (--n); // n must be greater than 0 here
}
n = parseInt(iterations / 8, 10);
if (n > 0) { // if iterations < 8 an infinite loop, added for safety in second printing
do {
testVal++;
testVal++;
testVal++;
testVal++;
testVal++;
testVal++;
testVal++;
testVal++;
}
while (--n); // n must be greater than 0 here also
}
}
@OllieJones
Copy link

OllieJones commented Apr 25, 2021

Thanks for this; good stuff.

How about ....

  let n = iterations & 0x7
  while (n-- > 0) {
     testVal++;
  }
  n = iterations >> 2
   while (n-- > 0) {
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
  }

Is there something less efficient about while (n--) { } over do { } while (--n) ?

@JamieMason
Copy link
Author

Hey @OllieJones.

Is there something less efficient about while (n--) { } over do { } while (--n) ?

I'm not sure to be quite honest, the best thing would be to create some benchmarks and compare. I wrote this script back in 2012 and a lot will have changed since then.

If you're curious, https://jsperf.com was the best place for benchmarking until a few years ago but it seems to be dead now, googling around I managed to find https://jsbench.me/.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment