Allocations in advent of code

Some alternatives:

  1. let block
julia> using BenchmarkTools

julia> @ballocated let 
       input = [3,4,3,1,2]
       histogram = [count(==(i),input) for i in 0:8]
       phase(day) = mod(day-1,9)+1
       for day in 1:256
          histogram[phase(day-2)] += histogram[phase(day)]
       end
       sum(histogram)
       end
224

  1. everthing in a function
julia> function main() 
       input = [3,4,3,1,2]
       histogram = [count(==(i),input) for i in 0:8]
       phase(day) = mod(day-1,9)+1
       for day in 1:256
          histogram[phase(day-2)] += histogram[phase(day)]
       end
       sum(histogram)
       end
       @ballocated main()
224
  1. the data outside the function, but as parameters:
julia> input = [3,4,3,1,2]
       histogram = [count(==(i),input) for i in 0:8]
       phase(day) = mod(day-1,9)+1
       function main(input,histogram)
       for day in 1:256
          histogram[phase(day-2)] += histogram[phase(day)]
       end
       sum(histogram)
       end
       @ballocated main($input,$histogram) # interpolate the input parameters! 
0

always using @ballocated from BenchmarkTools, to avoid computing compilation, etc.

2 Likes