# Avoid allocations

**URL:** <https://discourse.julialang.org/t/avoid-allocations/44187>\
**Category:** Performance\
**Created:** [August 3, 2020, 1:05pm UTC](https://discourse.julialang.org/t/avoid-allocations/44187 "2020-08-03T13:05:47Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![nhavt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nhavt/32/16356_2.png) [@nhavt](https://discourse.julialang.org/u/nhavt)\
**Post date:** [August 3, 2020, 1:05pm UTC](https://discourse.julialang.org/t/avoid-allocations/44187/1 "2020-08-03T13:05:47Z")

</div>

Hi there,

suppose that I have a `Float64` vector `x`. I wish to identify non-zero elements of this vector. Below are my proposal for that.

```julia
f1!(y,x) = y .= (x .!=0 )[:];
function f2!(y,x)
   @inbounds @simd for i ∈ eachindex(x) 
        if x[i]!=0
           y[i] = true
        end
    end
end

q = 43416;
x = Array(sprand(Float64, 1, q, 0.75));
y = falses(q);
@btime f1!($y,$x);
126.599 μs (5 allocations: 15.14 KiB)
@btime f2!($y,$x);
133.500 μs (0 allocations: 0 bytes)

```

As you can see, `f1!` is a bit faster than `f2!`. However, it requires a few allocations. So, my question here is whether it is possible to write a function that is as fast as f1 and does not require allocations? Thank you very much in advance!

---

<div class="post-metadata">

**Author:** ![pkofod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pkofod/32/2179_2.png) [@pkofod](https://discourse.julialang.org/u/pkofod)\
**Post date:** [August 3, 2020, 1:20pm UTC](https://discourse.julialang.org/t/avoid-allocations/44187/2 "2020-08-03T13:20:18Z")

</div>

`f1!(y,x) = map!(iszero, y, x)`

?

But maybe you need to think about why you needed that `[:]` 🙂 Hint: your x is not a vector.

edit:  
oops, yes  
`f1!(y,x) = map!(!iszero, y, x)`

---

<div class="post-metadata">

**Author:** ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)\
**Post date:** [August 3, 2020, 1:39pm UTC](https://discourse.julialang.org/t/avoid-allocations/44187/3 "2020-08-03T13:39:46Z")

</div>

Brilliant, this is as fast as fastest loop. I think you meant `f1!(y,x) = map!(!iszero, y, x)`, though.

---

<div class="post-metadata">

**Author:** ![nhavt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nhavt/32/16356_2.png) [@nhavt](https://discourse.julialang.org/u/nhavt)\
**Post date:** [August 3, 2020, 1:44pm UTC](https://discourse.julialang.org/t/avoid-allocations/44187/4 "2020-08-03T13:44:40Z")

</div>

Hi ,

> [@pkofod](#):
>
> oops, yes  
> `f1!(y,x) = map!(!iszero, y, x)`

wow, that is awesome! Indeed, `x` should be a vector. However, in my application, `x` is obtained from a matrix. Therefore, I used [:] to make it as a vector. Thank you very much for your help! 🙂
