duff's device

const duffDevice = (items, process) => {
  let iterations = Math.floor(items.length / 8);
  let startAt = items.length % 8;
  let i = 0;
  
  do {
    switch(startAt) {
      case 0 : process(items[i++]);
      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);
};

const process = (i) => {
      sum = sum + i;
}

const items = new Array(10000).fill(1);

let sum = 0;

const startCal = () => {
  sum = 0;
  
  console.time('1');
  duffDevice(items, process);
  console.log('sum', sum);
  console.timeEnd('1');

  sum = 0;
 
  console.time('2'); 
  for(var i = 0, l = items.length; i < l; i++) {
    process(items[i]);
  }
  console.log('sum', sum);
  console.timeEnd('2');
}

 

posted @ 2019-04-03 20:05  南辰_k  阅读(270)  评论(0编辑  收藏  举报