# Slow sum computation

I'm doing a simple OLS regression and I strikes my attention that this very simple computation takes several seconds to perform in Mathematica

Sum[(x[[i]] - Mean[x]) (y[[i]] - Mean[y]), {i, 1, 40}]/ Sum[(x[[i]] - Mean[x])^2, {i, 1, 40}]


The equivalent in Maple is instantaneous:

(sum((x[i]-Mean(x))*(y[i]-Mean(y)), i = 1 .. 40))/(sum((x[i]-Mean(x))^2, i = 1 .. 40))


Am I doing something wrong?

Since Sum holds its arguments, it ends up computing Mean[x] and Mean[y] in every step in the sum. Try
Total[(x - Mean[x])(y - Mean[y])]/Total[(x - Mean[x])^2]

which uses vectorized operations. In general, Sum is most suited to compute sums of symbolic quantities, sums with symbolic limits etc. Total or Tr is much faster for numeric stuff.