Bill Allombert on Sun, 01 May 2022 17:08:38 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: question about speed


On Sun, May 01, 2022 at 04:43:54PM +0200, Karim Belabas wrote:
> * Thomas Kellar [2022-05-01 16:18]:
> > I have code that looks like the below running billions
> > of times and the top one is a little faster than the bottom
> > one. This is not intuitive to me.  Is there any explanation?
> > 
> > if (a == b,
> >     return(0);
> > );
> > return(1);
> > 
> > why is the above faster:
> > and the below slower:
> > 
> > if (a == b,
> >     return(0);
> >    ,
> >    return(1);
> > );
> > 
> > Is that always the case?
> 
> I had the same explanation as Bill. To check my intuition, I ran the following
> quick test:
> 
>   f() = if (a==b,return(0),return(1));
>   g() = if (a==b,return(0));return(1);
>   h() = return(a!=b)   \\ or (better) 'a != b'; here, timings are the same

The internal GP bytecode compiler actually removes return() at end of
functions, so the code is actually

 f() = if (a==b,0,1);
 g() = if (a==b,return(0));1;
 h() = a!=b;

return() is slow so if a==b, f() is faster (by skipping the
return) while if a!=b g is faster (by skipping the "else" branch).

Cheers,
Bill.