# Avoid allocations

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.

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

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

5 Likes

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

4 Likes

Hi ,

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!