Mega Code Archive

 
Categories / Delphi / Examples
 

Optimize your code, use WITH

Title: Optimize your code, use WITH. Question: Another way to optimize my code? Answer: During the time that I have programming in Delphi have been able to learn some things, with the practices, of the books, of other persons and some something else but, by simple deduction. Something that actually suprise me is that the use of the With can increase considerably the speed in your programs since the sentences are executed quickly, enclosed between the begin and the end of the With. Why? I suposse that the compiler optimizes the chunk of code to the not to exist the reference completes to a given object since this alone is reference at beginning. If You do not believes me simply it prove this small chunk of code: WITHOUT OPTIMIZING: var i, e: Integer; tick1, tick2: Cardinal; begin Memo1.Lines.Clear; tick1 := GetTickCount; e:=0; for i:=0 to ListBox1.Items.Count-1 do if ListBox1.Selected[i] then begin Inc(e); end; tick2 := GetTickCount; Memo1.Lines.Add(Format('Found: %d',[e])); Memo1.Lines.Add(Format('Start : %.8d',[tick1])); Memo1.Lines.Add(Format('End : %.8d',[tick2])); Memo1.Lines.Add(Format('Diference : %.8d',[tick2 - tick1])); end; OPTIMIZED. var i, j, k, e: Integer; tick1, tick2: Cardinal; begin Memo2.Lines.Clear; tick1 := GetTickCount; With ListBox1 do Begin e:=0; for i:=0 to Items.Count-1 do if Selected[i] then begin Inc(e); end; end; tick2 := GetTickCount; Memo2.Lines.Add(Format('Ffound: %d',[e])); Memo2.Lines.Add(Format('Start : %.8d',[tick1])); Memo2.Lines.Add(Format('End : %.8d',[tick2])); Memo2.Lines.Add(Format('Diference : %.8d',[tick2 - tick1])); end; Obviously You must put a form and the necessary controls to fill the list and be carefull to use WITH. Currently I dont know if exists something document on this property, but in any case I send the suggestion.