How does Duff's device work?

前端 未结 11 1648
日久生厌
日久生厌 2020-11-22 04:56

I\'ve read the article on Wikipedia on the Duff\'s device, and I don\'t get it. I am really interested, but I\'ve read the explanation there a couple of times and I still do

11条回答
  •  感情败类
    2020-11-22 05:42

    The point of duffs device is to reduce the number of comparisons done in a tight memcpy implementation.

    Suppose you want to copy 'count' bytes from a to b, the straight forward approach is to do the following:

      do {                      
          *a = *b++;            
      } while (--count > 0);
    

    How many times do you need to compare count to see if it's a above 0? 'count' times.

    Now, the duff device uses a nasty unintentional side effect of a switch case which allows you to reduce the number of comparisons needed to count / 8.

    Now suppose you want to copy 20 bytes using duffs device, how many comparisons would you need? Only 3, since you copy eight bytes at a time except the last first one where you copy just 4.

    UPDATED: You don't have to do 8 comparisons/case-in-switch statements, but it's reasonable a trade-off between function size and speed.

提交回复
热议问题