Created
October 11, 2019 08:29
-
-
Save pluscai/355950e7f346e17c67399c1ee5464d01 to your computer and use it in GitHub Desktop.
JS中的 Duff's Device及其变体
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Duff’s device | |
*/ | |
function loop1() { | |
var result = []; | |
function process(value) { | |
result.push(value*2); | |
} | |
var items = [0,1,2,3,4,5,6,7,8]; | |
var iterations = Math.ceil(items.length / 8), | |
startAt = items.length % 8, | |
i = 0; | |
do { | |
switch (startAt) { | |
case 0: process(items[i++]); // process(0) i = 1 | |
case 7: process(items[i++]); | |
case 6: process(items[i++]); | |
case 5: process(items[i++]); | |
case 4: process(items[i++]); | |
case 3: process(items[i++]); | |
case 2: process(items[i++]); | |
case 1: process(items[i++]); | |
} | |
startAt = 0; | |
} while (--iterations); | |
console.log(result); | |
} | |
/* | |
Duff’s device的变体,比loop1快 40% | |
*/ | |
function loop2() { | |
var result = []; | |
function process(value) { | |
result.push(value*2); | |
} | |
var items = [0,1,2,3,4,5,6,7,8]; | |
var iterations = Math.floor(items.length / 8), | |
leftover = items.length % 8, | |
i = 0; | |
if(leftover > 0){ | |
do { | |
process(items[i++]) | |
}while (--leftover > 0) | |
} | |
do { | |
process(items[i++]); | |
process(items[i++]); | |
process(items[i++]); | |
process(items[i++]); | |
process(items[i++]); | |
process(items[i++]); | |
process(items[i++]); | |
process(items[i++]); | |
} while (--iterations); | |
console.log(result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment