# Which variable initialization is optimized away when variable unused?

**URL:** <https://discourse.julialang.org/t/which-variable-initialization-is-optimized-away-when-variable-unused/80587>\
**Category:** Performance\
**Tags:** optimization\
**Created:** [May 6, 2022, 4:28am UTC](https://discourse.julialang.org/t/which-variable-initialization-is-optimized-away-when-variable-unused/80587 "2022-05-06T04:28:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![FireCrumb](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/firecrumb/32/35370_2.png) [@FireCrumb](https://discourse.julialang.org/u/FireCrumb)\
**Post date:** [May 6, 2022, 4:28am UTC](https://discourse.julialang.org/t/which-variable-initialization-is-optimized-away-when-variable-unused/80587/1 "2022-05-06T04:28:14Z")

</div>

I have a method where `x` is used, but `y` isn’t used.

Why when I assign `sqrt(100)` to `y` then it’s ignored and not even executed (which is the desired behaviour), but when it’s assigned `collect(1:100)` then it is executed?

Is there an official separation between all the functions that _are_ optimized away when the variable isn’t used in the scope versus those that aren’t?

```julia
function f1(z)
    x = 5
    y = sqrt(100) # unused
    return z + x
end

@code_native f1(5)

```

output very short, and x value is inlined:

```julia
	.text
; ┌ @ In[2]:6 within `f1`
; │┌ @ int.jl:87 within `+`
	leaq	5(%rdi), %rax
; │└
	retq
	nopw	%cs:(%rax,%rax)
; └

```

but this one becomes huge output which means `collect` isn’t removed:

```julia
function f2(z)
    x = 5
    y = collect(1:10) # unused
    return z + x
end

@code_native f2(5)

```

---

<div class="post-metadata">

**Author:** ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)\
**Post date:** [May 6, 2022, 4:31am UTC](https://discourse.julialang.org/t/which-variable-initialization-is-optimized-away-when-variable-unused/80587/2 "2022-05-06T04:31:53Z")

</div>

semantically there is no difference. However, it is much harder to delete allocations, especially since `Array` allocations go through a `ccall` that makes some optimizations harder. That said, recent dev versions of Julia are getting better at doing escape analysis which is the required optimization to delete the allocation.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [May 6, 2022, 5:39am UTC](https://discourse.julialang.org/t/which-variable-initialization-is-optimized-away-when-variable-unused/80587/3 "2022-05-06T05:39:24Z")

</div>

[https://github.com/JuliaLang/julia/pull/43548](https://github.com/JuliaLang/julia/pull/43548)
