I have a case of unexplained memory allocation.  I am evaluating a 
polynomial that is 5th order in x and y.  The function does not allocate 
any memory if I have all the powers of x and the powers of y from 5 to 3, 
but if I add the y squared term, it starts allocating memory.  However, if 
I call the first version of the function and 
add the y square term to that result, the function does not allocate 
memory.  I'm not sure how to explain this behavior.

Here is a test code:

# evaluate a polynomial of x and y (does not allocate)
function calcp1{Tmsh}(coords::AbstractArray{Tmsh}, alpha_x, alpha_y, t)
  x = coords[1]
  y = coords[2]
  return x.^5 + x^4 + x^3 + x^2 + x + 1 + y^5 + y^4 + y^3
end

# evaluate t
function calcp2{Tmsh}(coords::AbstractArray{Tmsh}, alpha_x, alpha_y, t)
  x = coords[1]
  y = coords[2]
  # this allocates
  return x.^5 + x^4 + x^3 + x^2 + x + 1 + y^5 + y^4 + y^3 + y^2

  # this does *not* allocate
  #return calcp1(coords, alpha_x, alpha_y, t) + y^2
end

function runtest()

  ntrials=10000
  coords = zeros(2)
  alpha_x = 1.0
  alpha_y = 1.0
  t = 0.0
  sum = 0.0
  @time for i=1:ntrials
    coords[1] = i
    sum += calcp1(coords, alpha_x, alpha_y, t)
  end

  sum2 = 0.0
  @time for i=1:ntrials
    coords[1] = i
    sum2 += calcp2(coords, alpha_x, alpha_y, t)
  end

  return sum, sum2
end

println("Warming up")
runtest()
println("Final results")
runtest()


The output is:
Final results
  0.002028 seconds
  0.002569 seconds (80.00 k allocations: 1.221 MB)

Jared Crean

Reply via email to