[comp.lang.pascal] Fast Char access in strings

ZCCBJSB%EB0UB011.BITNET@cunyvm.cuny.edu (Josep Sau B.) (04/19/91)

Craig R.Nelson (mwizard@eecs.ee.pdx.edu) said in a message
date Fri, 19 Apr 91 00:54:10 -0700 (personal to ZCCBJSB@%EB0UB011 ?):

> ...
> You were very correct about getting a string back from a Copy()
> call...
> ...
> The "0" byte of a string ALWAYS contains the length of the current
> string. Not the declared length, but the actual length at runtime
> that was assigned.
>
> Nifty trick:  Want to assign a string to zero length quick ?
> If you do this:
>   S:= '';
> it actually creates the '' string, then does a byte copy,
> and then assigns the
> length to the "0" byte of S.  Now why not do this instead :
>   S(.0.):= CHR(0);
> Trye doing this about 30000 times in a loop and compare it with
> the other method above.  Nice trick, don't you think ?

You're right. Juggling with the length CHAR in the STRING(.0.)
allows to implement other routines faster than using the
STRING functions or the concetantion operator '+'.

Try for example this two routines to generate a string
containing Len repetitions of CHAR Ch:

FUNCTION FastCharStr (Ch :CHAR; Len :BYTE) :STRING;
 VAR s :STRING;
 BEGIN
  BYTE(s(.0.)) := Len;
  FillChar(s(.1.), Len, Ch);
  FastCharStr := s;
 END;

FUNCTION SlowCharStr (Ch :CHAR; Len :BYTE) :STRING;
 VAR s :STRING;
 VAR i :BYTE;
 BEGIN
  s := '';
  FOR i := 1 TO Len DO s := s + Ch;
  SlowCharStr := s;
 END;

Tricks like this are alright, but I think that so implementation
dependent features should be restricted to well isolated and
full-tested routines to do punctual processes.

-- Josep Sau

'...and he amazed with the marvels that are in the world,
    and he asked about things he did not understand,
    and he taught about things he knew.'
 Raimundus Lulius - _Llibre_de_Meravelles_