Skip to content

::Function argument in recursive function is expensive #18207

Closed
@KristofferC

Description

Just having a function as an argument in a recursive function creates an allocation at each call. This is a minimized example from one of my packages:

function knn_kernel2!(index::Int)
    index > 1_000_000 && return
    knn_kernel2!(2*index)
    knn_kernel2!(2*index+1)
    return
end

function knn_kernel2!(index::Int,
                      skippoint::Function)
    index > 1_000_000 && return
    knn_kernel2!(2*index, skippoint)
    knn_kernel2!(2*index+1, skippoint)
    return
end
julia> @time knn_kernel2!(1)
  0.003125 seconds (4 allocations: 160 bytes)

julia> @time knn_kernel2!(1, x->false)
  0.181919 seconds (2.00 M allocations: 30.511 MB, 2.16% gc time)

Is there anyway to workaround this?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions