# What is the fastest way to perform unary operation inplace?

**URL:** <https://discourse.julialang.org/t/what-is-the-fastest-way-to-perform-unary-operation-inplace/55139>\
**Category:** Performance\
**Created:** [February 12, 2021, 11:02am UTC](https://discourse.julialang.org/t/what-is-the-fastest-way-to-perform-unary-operation-inplace/55139 "2021-02-12T11:02:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![encendre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/encendre/32/21893_2.png) [@encendre](https://discourse.julialang.org/u/encendre)\
**Post date:** [February 12, 2021, 11:02am UTC](https://discourse.julialang.org/t/what-is-the-fastest-way-to-perform-unary-operation-inplace/55139/1 "2021-02-12T11:02:47Z")

</div>

What is the fastest way to perform unary operation inplace ?  
I have tried the followings

```julia
b = rand(1000000)
@time b = -b
# 0.011017 seconds (2 allocations: 7.629 MiB)

@time b = (-).(b)
# 0.012952 seconds (2 allocations: 7.629 MiB)

@time b .-= 2 .* b
# 0.002173 seconds

@time begin
	for i in 1:length(b)
		@inbounds b[i] = -b[i]
	end
end
# 0.001698 seconds

```

the first and the second allocate a new array, the thrid use a trick that cannot be extended to all unary operators and the fourth is not as concise as one would like it to be.

---

<div class="post-metadata">

**Author:** ![encendre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/encendre/32/21893_2.png) [@encendre](https://discourse.julialang.org/u/encendre)\
**Post date:** [February 12, 2021, 11:09am UTC](https://discourse.julialang.org/t/what-is-the-fastest-way-to-perform-unary-operation-inplace/55139/2 "2021-02-12T11:09:16Z")

</div>

Never mind i found it

```julia
@time @. b = -b
# 0.001678 seconds

# or
@time b .= (-).(b)
# 0.001670 seconds

```
