Skip to content

New function Base.unsafe_wrap! to avoid unnecessary heap allocations #28305

Closed
@MartinOtter

Description

@MartinOtter

If a C-function calls many times a Julia function and passes C-arrays, for example, when performing simulation, optimization, model-based controllers etc. (e.g. this case happens with the Sundials integrators, see e.g. issue https://github.com/JuliaDiffEq/Sundials.jl/pull/179), then C-arrays must be wrapped to Julia arrays. This is performed with the existing Base.unsafe_wrap(..) function. However, this function returns a Julia array and therefore allocates heap memory. In a typical simulation with Sundials IDA or CVODE this happens, say, 1000 - 10000 times for 3 arrays leading to many small heap allocations that dominate the function evaluation cost for smaller models. This performance issue could be fixed, if the C-array pointer could be replaced in an unsafe_wrap(..)ed array:

unsafe_wrap!(array, pointer::Ptr{T})

It is assumed that array is an existing Julia array generated with the unsafe_wrap(..) function with keyword argument own=false. Function unsafe_wrap!(..) changes the existing pointer to the array data to argument pointer. Hereby, it is assumed that the length of the data remains the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    arrays[a, r, r, a, y, s]

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions