# \`maximum!\` allocates

**URL:** <https://discourse.julialang.org/t/maximum-allocates/14191>\
**Category:** Performance\
**Tags:** question\
**Created:** [August 28, 2018, 3:16pm UTC](https://discourse.julialang.org/t/maximum-allocates/14191 "2018-08-28T15:16:31Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![e3c6](https://avatars.discourse-cdn.com/v4/letter/e/e79b87/32.png) [@e3c6](https://discourse.julialang.org/u/e3c6)\
**Post date:** [August 28, 2018, 3:16pm UTC](https://discourse.julialang.org/t/maximum-allocates/14191/1 "2018-08-28T15:16:32Z")

</div>

I get allocations, but I don’t understand why since it is writing the results in a preallocated array.

```julia
X = rand(10,3,4); x= rand(1,3,4);
@btime maximum!($x,$X)
# 452.492 ns (6 allocations: 240 bytes)

```

---

<div class="post-metadata">

**Author:** ![Paethon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/paethon/32/9278_2.png) [@Paethon](https://discourse.julialang.org/u/Paethon)\
**Post date:** [August 28, 2018, 3:39pm UTC](https://discourse.julialang.org/t/maximum-allocates/14191/2 "2018-08-28T15:39:55Z")

</div>

Deep down, following lots of function calls, `maximum!` calls the function `mapfirst!` and that allocates memory

> <https://github.com/JuliaLang/julia/blob/3ab56f19a81a1d658a02750b48abbd63950ef248/base/reducedim.jl#L221>

You can prevent that by calling `maximum!(x, X, init=false)` but I think you have to ensure manually that `x` does not contain a value bigger than any value in `X` (but I am not completely sure about that to be honest)

---

<div class="post-metadata">

**Author:** ![e3c6](https://avatars.discourse-cdn.com/v4/letter/e/e79b87/32.png) [@e3c6](https://discourse.julialang.org/u/e3c6)\
**Post date:** [August 28, 2018, 3:44pm UTC](https://discourse.julialang.org/t/maximum-allocates/14191/3 "2018-08-28T15:44:55Z")

</div>

I raised an issue, [maximum! allocates · Issue #28928 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/28928)

---

<div class="post-metadata">

**Author:** ![Paethon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/paethon/32/9278_2.png) [@Paethon](https://discourse.julialang.org/u/Paethon)\
**Post date:** [August 28, 2018, 4:04pm UTC](https://discourse.julialang.org/t/maximum-allocates/14191/4 "2018-08-28T16:04:56Z")

</div>

I am not really sure this is an issue. `maximum!` never claims to not allocate memory. And those are all just temporary allocations that are freed as soon as `mapfirst!` has finished …

---

<div class="post-metadata">

**Author:** ![e3c6](https://avatars.discourse-cdn.com/v4/letter/e/e79b87/32.png) [@e3c6](https://discourse.julialang.org/u/e3c6)\
**Post date:** [August 28, 2018, 4:13pm UTC](https://discourse.julialang.org/t/maximum-allocates/14191/5 "2018-08-28T16:13:50Z")

</div>

In principle the allocation could affect performance.  
Those allocations don’t have to wait for GC?
