[fpc-pascal] Can FPC optimize: if (s[i]='a') or ...

Rainer Stratmann rainerstratmann at t-online.de
Mon Apr 15 11:48:35 CEST 2019


On Sonntag, 14. April 2019 21:35:43 CEST wkitty42 at windstream.net wrote:
> On 4/14/19 7:28 AM, Rainer Stratmann wrote:
> > On Samstag, 13. April 2019 22:30:55 CEST Alexey Tor. wrote:
> >> E.g. i have a loop which test each s[i] char for several cases: 'a',
> >> 'b', 'c'.
> >> 
> >> for i:= 1 to length(s) do
> >> 
> >> if (s[i]='a') or (s[i]='b') or (s[i]='c') then ...
> >> 
> >> Can FPC optimize it so it only reads s[i] once (to register), not 3
> >> times?
> > 
> > You can optimise by yourself.
> > 
> > var
> > 
> >   c : char;
> >   l : longint;
> > 
> > begin
> > 
> >   l := length( s );
> >   for i := 1 to l do
> >   
> >    c := s[ i ];
> >    if ( c = 'a' ) or ( c = 'b' ) or ( c = 'c' ) then ...
> 
> this looks like it will read three times like the original instead of once
> like using the IN set operation... it is still stepping through each one of
> the comparison steps instead of just doing a set match...

It is at least better than reading s[ i ] at every compare operation.
Feel free to make more optimizations if there is a chance.
For example the IN operation.

if c in ['a', 'b', 'c'] then ...

You have to know the whole code to decide if it makes sense to drop the var c 
completely.



More information about the fpc-pascal mailing list