Reducing Allocation

Out of curiosity, is it possible to make the function zero allocation? The output excludes compile time.

using StatsPlots,Random, BenchmarkTools
# using TimerOutputs
function createPath(S, r, sigma, T, n,sim)
    h = T / n
    u = exp((r - sigma^2/2)*h + sigma * sqrt(h))
    d = exp((r - sigma^2/2)*h - sigma * sqrt(h))

    p_star = (exp(r*h) - d) / (u - d)

    path = zeros(n+2) #Array{Float64}(undef,n + 2)

    #add in the starting price
    path[1] = S
    p = plot() 
    for i in 1:sim
        for j in 2:n+2
#             if rand() < p_star
                #then we go up
                path[j] = path[j-1] * (rand() < p_star ?  u : d)
#             path[2:n+2] = path[1:n+1] .* [x  < p_star ?  u : d for x in rand(n+1)]'
#                 path[k] = path[k-1] * d
#             end
        plot!(p, path,w=1,primary=true,legend=false);  
    plot!(p, title="Stock Price Paths", xlabel="Period", ylabel="Price",size=[1000,500],w=1);
    return p
@time createPath(100.0, 0.08, 0.3, 1.0, 1000,100)
  0.120412 seconds (236.19 k allocations: 14.836 MiB, 11.75% gc time)

Plotting is surely going to allocate.

1 Like

@kristoffer.carlsson: Thanks. I managed to check that by using TimerOutput package.

You also create a 1000-element vector inside the function, which allocates. If you want to get rid of that, you need to pre-allocate it and pass it into the function.

Still, that’s nothing compared to the plotting, I guess.

@DNF: absolutely true that plotting uses much bigger allocation than the vector.