NearestNeighbors.jl - Can I formulate this in a way which makes it allocate less?

Hello!

I am using a library called NearestNeighbors to calculate neighbouring points. A simple script below shows the general idea of what I want to do:

using NearestNeighbors
using StaticArrays


function help_me_allocate_less()
    nCoords  = 3000
    coordsSA = [SVector{3,Float64}(rand(),rand(),rand()) for i in 1:nCoords]
    R = 0.2
    balltree = BallTree(coordsSA,reorder = false)
    idxs = inrange(balltree,coordsSA, R, false)

    for t = 1:100
        if mod(t,8) == 0
            balltree = BallTree(coordsSA,reorder = false)
            idxs = inrange(balltree, coordsSA, R, false)
        end
        coordsSA = [SVector{3,Float64}(rand(),rand(),rand()) for i in 1:nCoords]
    end
end

@time help_me_allocate_less()

And when I run this:

 @time help_me_allocate_less()
  0.270642 seconds (261.25 k allocations: 73.013 MiB, 10.49% gc time)

Would it be possible in some way to “replace” balltree and idxs “in place” such that it does not allocate that much?

Kind regards

Why do you need to recreate balltree in each loop iteration, in your example you are not modifying the inputs ro BallTree?

1 Like

Sorry, the example was a bit too simple. I have to update the balltree since “coordsSA” is changing.

I updated the example to reflect that now, thanks!