Hello guys

Hello guys,

Is it a good idea caching calls to Length(Array)? Can I end up preventing the compiler from doing some optimizations like avoiding bounds checking (once you will never overflow a array, so the value returned won't jump off the bounds)?

Does the Delphi compilers cache Length(Array) call in Loop conditional? I mean ~>
in this loop
while(i < Length(Array)) do ...

Will Length() get called everytime the loop runs? Has anyone ever experienced any improvement with this optimization? Or is it a premature optimization?

Thanks in advance :D

Comments

  1. The easiest way to find out is looking at the generated assembler code.
    (I have no idea, I never looked. But I tend to assign string, array and list lengths to a variable so I have less to type.)

    ReplyDelete
  2. No, the Delphi compiler does not cache length(Array) in "while(i < Length(Array)) do" since the Array length may change within the loop. So you should better use a local variable. Of course, a "for i := 0 to high(Array)" may be enough in most cases.
    But in modern versions of Delphi, length(Array) is inlined, so only slightly slower than a local variable. But usually I use a local variable if the length() is called more than once. This may be found as premature optimization in practice, since the gain may be negligeable...

    ReplyDelete
  3. The virtues of premature optimisation...

    ReplyDelete
  4. Bound checking is done when a value of the array is accessed, not when Length(..) is called.

    ReplyDelete
  5. I think remember High and Low aren't inlined. A for loop caches the end bound

    ReplyDelete
  6. David Berneda High(), when applied to a string, is an inlined function AFAIR.

    ReplyDelete
  7. A. Bouchez yep ! and ouch ! in Berlin 10.1 array High is also inlined. Good !

    ReplyDelete
  8. It's good to cache things that 1) are expensive to calculate and 2) are unlikely to change.  Getting the length of an array is not 1), and in many cases isn't 2) either.

    ReplyDelete
  9. Apart from the performance there is also maintainability to keep in mind. Computer power is cheap, developer time isn't. So, keeping the code readable and as easily to understand as possible might be much more important than a few clock cycles. We are talking Delphi here after all, whose compiler isn't known for the best execution speed anyway.

    ReplyDelete

Post a Comment