Pass cache to function

Hi!
I have a function which allocates a cache for calculations as

function f(x::AbstractArray)
  cache = zeros(length(x))
  # do some calculations
end

I now want to call this function very often (not in parallel) so I want to pre allocate the cache and pass it to the function, e.g. as

function f(x::AbstractArray; cache=zeros(length(x)))
  # do some calculations
end

Is this a legitimate way to do it? Can I run into some performance issues/type instabilities?

Thanks is advance!

1 Like

This is a legitimate way to do this. You might want to rename the function to f! if you are changing the pre-allocated array within the function.

1 Like

Thanks for the quick answer! Are you sure about the renaming? I am only modifying a cache, which is an optional argument. If it is not given by the caller, no modifications of arguments of the function is done.

The naming convention is merely a guideline. You may choose to not rename it if you feel that this obfuscates the use case.

OK! Cheers!