Stackoverflow: Why doesn’t the optimizer eliminate High in a loop?


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+} .

stackoverflow1 Stackoverflow: Why doesn't the optimizer eliminate High in a loop? assembly language delphi implementation interpreter / compiler programming languages windows

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.

stackoverflow2 Stackoverflow: Why doesn't the optimizer eliminate High in a loop? assembly language delphi implementation interpreter / compiler programming languages windows

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).

stackoverflow3 Stackoverflow: Why doesn't the optimizer eliminate High in a loop? assembly language delphi implementation interpreter / compiler programming languages windows

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).

stackoverflow4 Stackoverflow: Why doesn't the optimizer eliminate High in a loop? assembly language delphi implementation interpreter / compiler programming languages windows

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.

stackoverflow5 Stackoverflow: Why doesn't the optimizer eliminate High in a loop? assembly language delphi implementation interpreter / compiler programming languages windows

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
546 words
Last Post: Compute e Again
Next Post: Data Types in Delphi XE3, Win32 and Win64

The Permanent URL is: Stackoverflow: Why doesn’t the optimizer eliminate High in a loop?

Leave a Reply