Does Duff Device work in other languages?

Many years ago, working on the problem of tight I / O graphics, Tom Duff launched a loop and created the Duff Device as follows:

dsend(to, from, count) char *to, *from; int count; { int n = (count + 7) / 8; switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); } } 

(Note that this uses the parameters of the old-style function - this is not an error.)

This coding comes directly from thinking in assembler and coding in C and depends on case case. Can this kind of creativity in alternating management structures work in any other languages?

+7
c
source share
5 answers

You can do this in any language that supports GOTO computed operators (Fortran, some BASIC, etc.)

+5
source share

It works in C ++.

Please note that the generated code depends on your compiler. In particular, when I compiled the Duff device using GCC-oriented ARM architectures, the resulting ARM assembler was suboptimal (I think GCC turned it into a jump table) at any optimization level.

In the end, I just passed the encoding to the assembler.

+4
source share

A Duff device is essentially a computed goto that can be done in many other languages ​​- assembly (of course) and FORTRAN is a couple that supports them directly.

+3
source share

I used it very successfully in JavaScript to speed up the processing of a large array. I would like to use it in C #.

+3
source share

Even if it cannot be used this way, you can have two loops:

 dsend(to, from, count) char *to, *from; int count; { int n; for(n=0; n!=count/8; n+=8){ *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; } for(; n!=count; n++) { *to = *from++; } } 

I am sure that this will be somewhat slower with a lower count , but it is somewhat readable, somewhat more portable in different languages ​​and gives very similar benefits with a large count .

0
source share

All Articles