[fpc-devel] about commit r29324

Michael Van Canneyt michael at freepascal.org
Sun Dec 28 16:20:20 CET 2014



On Sun, 28 Dec 2014, Sergei Gorelkin wrote:

> 28.12.2014 17:36, Michael Van Canneyt пишет:
>>
>>
>> On Sun, 28 Dec 2014, Mattias Gaertner wrote:
>>
>>> Hi,
>>>
>>> forwarded from Zeljko:
>>>
>>> It's about fpc issue
>>> http://bugs.freepascal.org/view.php?id=26370
>>>
>>> It seems that TVariantArrayIterator.AtEnd loops for all Dims for no 
> reason, so have
>>> impact on performance.
>>>
>>> *current implementation*
>>> function TVariantArrayIterator.AtEnd: Boolean;
>>> var
>>>   i : sizeint;
>>> begin
>>>   result:=false;
>>>   for i:=0 to Pred(Dims) do
>>>     if Coords^[i] >= Bounds^[i].LowBound + Bounds^[i].ElementCount then
>>>       result:=true;
>>> end;
>>>
>>> *optimized implementation*
>>> function TVariantArrayIterator.AtEnd: Boolean;
>>> var
>>>   i : sizeint;
>>> begin
>>>   result:=false;
>>>   for i:=0 to Pred(Dims) do
>>>     if Coords^[i] >= Bounds^[i].LowBound + Bounds^[i].ElementCount then
>>>     begin
>>>       result:=true;
>>>       break;
>>>     end;
>>> end;
>>
>> Or, better yet
>>
>> var
>>    i : sizeint;
>> begin
>>    Result:=false;
>>    I:=0;
>>    While (Not Result) and (I<=Pred(Dims)) do
>>      begin
>>      Result:= Coords^[i] >= Bounds^[i].LowBound + Bounds^[i].ElementCount;
>>      Inc(I);
>>      end;
>> end;
>>
>> People really don't seem to get booleans, and why they scorn "While" is 
> beyond me. All these ugly
>> "break" statements :(
>>
>> You may optimize even more by calculating Max:=pred(dims) once and doing 
> I<=Max;
>>
> Actually, in this particular case performance optimizations are pretty 
> useless:
> - TVariantArrayIterator.AtEnd method is called just once to decide whether it 
> is necessary to 
> iterate the array. Its usage is not typical for iterators, where such methods 
> are called in a loop.
> - To return False, it has to iterate all dimensions. After that, iterating 
> the data of variant array 
> will take orders of magnitude more time.
> - Early exit can happen only for arrays with zero-sized dimension, which is 
> basically invalid and 
> indicates programmer's mistake elsewhere.

All this may of course be true for this particular case, but it's in general always better 
to have optimized code. So I have committed the code as I replied it (after testing 
that the test program still performs as expected).

Michael.


More information about the fpc-devel mailing list