Karim Belabas on Sat, 03 Jan 2026 16:32:14 +0100


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

Re: function call (marginally) faster than algebraic expression


* Ruud H.G. van Tol [2026-01-03 14:25]:
> I noticed that
> 
>   lista1(n)= vector(n+1, i, binomial(i, 2)^2);
> 
> is 20% faster than variants like
> 
>   lista2(n)= vector(n+1, i, ((i^2-i)/2)^2);
> 
> in my GP/PARI v.2.17.3 (tested with n=10^6).
> 
> Is that as expected?

For small inputs, yes. Calls to libpari functions have little overhead
(user functions a little more so) and they use low-level optimizations
internally.

For instance, here, binomial(i,2) for i > 0 is (essentially) computed as

 ((i & 1)? i: i-1) * (i >> 1)

N.B.

  lista2(n)= vector(n+1, i, ((i^2-i) >> 1)^2);

will fare a bit better but still slower of course.

Cheers,

    K.B.

> P.S. And with some storage, much slower:
> 
>   lista3(n)= my(s=0); vector(n+1, i, s+=(i-1)^3);

Lots of extra copies involved...

-- 
Pr. Karim Belabas, U. Bordeaux, Vice-président en charge du Numérique
Institut de Mathématiques de Bordeaux UMR 5251 - (+33) 05 40 00 29 77
http://www.math.u-bordeaux.fr/~kbelabas/