I have asked a question in stackoverflow.com and it brings some discussions. The question is about the code efficiency generated by Delphi compilers and I’ve tried the following simple example on Delphi 2007 and Delphi XE3 (the latest version), both produced similar assembly code having the optimization turned on, e.g {$O+} .
The above code doesn’t have actual use but just illustrates the idea. The compilers still call expensive call to @DynArrayHigh function which returns the upper bound of the dynamic array.
This is not good because we are not changing, obviously in this case, the array in the loop. It would be better to store the length of the array in a local variable to avoid repetitive calls to the High function. The above assembly code is generated when DEBUG mode is turned on (Ctrl+Alt+D to see dis-assembly) . The following is quite similar when the compiler switch is set to RELEASE (using F8/F7 to step into to see the code).
The answer proposes that, the compiler shouldn’t attempt to optimize this because the array might be changed in the loop or somewhere else (if the array is declared as a global variable, accessed by other threads).
However, since this is a local variable, we can see that whether this can be changed, thus it is possible to optimize this manually. The compilers still are not clever enough. Some might argue that High() is similar to Length() which is a non-deterministic function, as opposed to SizeOf(). Therefore, it is up to the programmers to optimize these manually.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Compute e Again
Next Post: Data Types in Delphi XE3, Win32 and Win64