# Pass cache to function

**URL:** <https://discourse.julialang.org/t/pass-cache-to-function/41934>\
**Category:** Performance\
**Created:** [June 23, 2020, 1:12pm UTC](https://discourse.julialang.org/t/pass-cache-to-function/41934 "2020-06-23T13:12:20Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![jamblejoe](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jamblejoe](https://discourse.julialang.org/u/jamblejoe)\
**Post date:** [June 23, 2020, 1:12pm UTC](https://discourse.julialang.org/t/pass-cache-to-function/41934/1 "2020-06-23T13:12:20Z")

</div>

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

```julia
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

```julia
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!

---

<div class="post-metadata">

**Author:** ![jishnub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jishnub/32/33620_2.png) [@jishnub](https://discourse.julialang.org/u/jishnub)\
**Post date:** [June 23, 2020, 1:18pm UTC](https://discourse.julialang.org/t/pass-cache-to-function/41934/2 "2020-06-23T13:18:04Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jamblejoe](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jamblejoe](https://discourse.julialang.org/u/jamblejoe)\
**Post date:** [June 23, 2020, 1:20pm UTC](https://discourse.julialang.org/t/pass-cache-to-function/41934/3 "2020-06-23T13:20:16Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jishnub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jishnub/32/33620_2.png) [@jishnub](https://discourse.julialang.org/u/jishnub)\
**Post date:** [June 23, 2020, 1:22pm UTC](https://discourse.julialang.org/t/pass-cache-to-function/41934/4 "2020-06-23T13:22:29Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jamblejoe](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jamblejoe](https://discourse.julialang.org/u/jamblejoe)\
**Post date:** [June 23, 2020, 1:22pm UTC](https://discourse.julialang.org/t/pass-cache-to-function/41934/5 "2020-06-23T13:22:49Z")

</div>

OK! Cheers!
