[fpc-pascal] Array clearing
noreply at z505.com
noreply at z505.com
Wed Apr 12 15:05:45 CEST 2017
On 2017-04-01 02:39, Sven Barth via fpc-pascal wrote:
> Am 01.04.2017 05:42 schrieb "Ryan Joseph"
> <ryan at thealchemistguild.com>:
>> As far as the compiler is concerned what’s the difference between
> clearing an array using a for-loop vs. FillChar? It seems like
> iterating the array would be slower but what does FillChar do exactly
> and is it faster? The primary concern here is that the memory
> originally allocated (using SetLength right?) remains in the same
>> list: array of integer;
>> SetLength(list, 10);
>> for i := 0 to high(list) do
>> list[i] := 0;
>> FillChar(list, Length(list) * sizeof(integer), 0);
> It totally depends on the type. In case of primitive types like
> integers there is indeed only the performance difference (though if
> you know that the element size is four FillDWord could be even faster,
> depending on the implementation in the RTL).
> If you have managed types however or class instances the result of the
> FillChar (or equivalent) would be memory leaks.
> Plase also note that after a SetLength the new elements are already 0
> (or equivalent).
Since fillchar is not a general way to clear an item it almost seems
like pascal needs a way to clear things generically, such as Array.clear
But I guess this would be reinventing OOP, or Ruby where everything is
an object and can have .Something tacked on to it.
I've never been a fan of things like fillchar as it seems like a
reinvention of something more like Clear() and mistakes can easily be
made when you use complex function like this:
fillchar(something, something * something, 0)
instead of a more simpler:
You could, put the array inside a class/object I suppose and make a
clear method... or use an old pascal object with a clear method on the
stack so no free/create is required.
All this seems to be maybe either reinventing GoLang or Ruby though, or
To me, fillchar doesn't actually say anything sensible about what the
code is doing... "Clear" or "Default" (I think delphi is implementing
something like this in later versions) says exactly what the code is
doing. FillChar is some obscure old 1970's/80's pascal function that
really doesn't tell what you are doing, unless you are an old pascal
programmer who knows it from long ago. I'm skeptical of these old ways
of doing things.. Imagine a newcomer to pascal who did not program in
the 1980's... He sees "fillchar" in the program... Does that code even
tell this learner of pascal what is happening? What's a "char" have to
do with an array that may not have anything to do with chars?
Just my opinion and, possibly rant. Apologies. Rant not directed at
anyone in particular, just I'm skeptical of this whole fillchar thing...
Even though I use it myself. Usually in a clear() wrapper of my own, to
make the code more clear... Or a setdefault() or default() like function
More information about the fpc-pascal