# Type stability and assignments of functions

**URL:** https://discourse.julialang.org/t/type-stability-and-assignments-of-functions/58719
**Category:** New to Julia
**Tags:** type-stability
**Created:** [April 6, 2021, 10:12pm UTC](https://discourse.julialang.org/t/type-stability-and-assignments-of-functions/58719 "2021-04-06T22:12:20Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![matthias314](https://avatars.discourse-cdn.com/v4/letter/m/a88e4f/32.png) [@matthias314](https://discourse.julialang.org/u/matthias314)
#### Post date: [April 6, 2021, 10:12pm UTC](https://discourse.julialang.org/t/type-stability-and-assignments-of-functions/58719/1 "2021-04-06T22:12:20Z")

</div>

I’m trying to understand how assigning a function to another variable affects type stability. Consider the following example:

```julia
f(x) = x # any function
g = f
ff(x) = f(x)
gg(x) = g(x)

```

Then

```julia
@code_warntype f(1) # good
@code_warntype g(1) # good
@code_warntype ff(1) # good
@code_warntype gg(1) # bad

```

More precisely, for `gg` I get

```julia
Body::Any
1 ─ %1 = Main.g(x)::Any

```

In the application I have in mind, `f` would be a closure returned by some function, and `g` is the name I give to it early on in my code. Then using `g` in other functions like `gg` would lead to performance problems. Is there a way around this?

---

<div class="post-metadata">

### Author: ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)
#### Post date: [April 6, 2021, 10:18pm UTC](https://discourse.julialang.org/t/type-stability-and-assignments-of-functions/58719/2 "2021-04-06T22:18:43Z")

</div>

> [@matthias314](#):
>
> `f(x) = x # any function`

This is slightly tricky. Defining a function like this implicitly makes `f` a `const` (when at global scope). Using `const` globals is totally fine for performance.

> [@matthias314](#):
>
> `g = f`

This assignment creates a new _non-const_ variable named `g` with the same value as `f`. Your use of `g` within `gg` thus constitutes the use of a non-constant global variable, which is why type inference fails.

In global scope, you can do:

```julia
const g = f

```

In local scope (e.g. inside a function), you don’t need to worry about this at all.

---

<div class="post-metadata">

### Author: ![matthias314](https://avatars.discourse-cdn.com/v4/letter/m/a88e4f/32.png) [@matthias314](https://discourse.julialang.org/u/matthias314)
#### Post date: [April 6, 2021, 10:23pm UTC](https://discourse.julialang.org/t/type-stability-and-assignments-of-functions/58719/3 "2021-04-06T22:23:41Z")

</div>

Great, thanks!
