A For loop is used in Javascript, which can have a significant impact on performance when there are many data records to loop. At this point we can consider expanding the for loop, where the Duff device (Duff device) will be used.
Let's start with a small example, with a For loop:
function Process (data) {Htmlstr+ = data +"<br/>"; //div = document.getElementById ("mydiv"); //div.innerhtml + = data + "<br/>";} function Forloop (values) {Console.time ('forlooptest'); for(vari =0; i < values.length; i++) {process (values[i]); } div.innerhtml=Htmlstr; Console.timeend ('forlooptest'); }
This for loop can be expanded with Duff as follows, (Jeff Greenberg implements the Duff device with JavaScript, which is implemented by Jeff)
function Duff (values) {Console.time ('Duff Test'); variterations = Math.ceil (Values.length/8); varStartAt = values.length%8; vari =0; Do { Switch(startAt) { Case 0: Process (values[i++]); Case 7: Process (values[i++]); Case 6: Process (values[i++]); Case 5: Process (values[i++]); Case 4: Process (values[i++]); Case 3: Process (values[i++]); Case 2: Process (values[i++]); Case 1: Process (values[i++]); } startAt=0; } while(--iterations >0); Div.innerhtml=Htmlstr; Console.timeend ('Duff Test'); }
Andrew b.king later improved the Duff device, which is said to improve the DFF device, performance can reach about 40% ... Our corresponding code is as follows:
function Newduff (values) {Console.time ('test1'); variterations = Math.floor (Values.length/8); varleftover = values.length%8; vari =0; if(Leftover >0) { Do{process (values[i++]); } while(--leftover >0); } Do{process (values[i++]); Process (Values[i++]); Process (Values[i++]); Process (Values[i++]); Process (Values[i++]); Process (Values[i++]); Process (Values[i++]); Process (Values[i++]); } while(--iterations >0); Div.innerhtml=Htmlstr; Console.timeend ('test1') }
Specific test data, the next time, the home of the old machine, it is not carried, the elderly crash ...
JavaScript loop unrolling Duff device Javascript Duff Appliance Loop Expansion