# For loop with variable range so slow

**URL:** https://discourse.julialang.org/t/for-loop-with-variable-range-so-slow/136149
**Category:** General Usage
**Created:** [March 11, 2026, 12:16pm UTC](https://discourse.julialang.org/t/for-loop-with-variable-range-so-slow/136149 "2026-03-11T12:16:12Z")
**Posts on this page:** 1
**Showing post:** 6

<div class="post-metadata">

### Author: ![ForceBru](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/forcebru/32/21389_2.png) [@ForceBru](https://discourse.julialang.org/u/ForceBru)
#### Post date: [March 11, 2026, 1:06pm UTC](https://discourse.julialang.org/t/for-loop-with-variable-range-so-slow/136149/6 "2026-03-11T13:06:58Z")

</div>

Yet another option is to make the global variable typed:

```Julia
julia> n_T::Int = 100 # assign type!
100

julia> for i = 1:2
                  @time begin
                      n = 1
                      for j = 1:n_T
                          n += j
                      end
                  end
              end
  0.000000 seconds
  0.000000 seconds

```

You can subsequently assign another integer to `n_T` and it’ll remain fast.

As discussed here ([Why is there a performance difference between global and local variables in non-interactive Julia programs?](https://discourse.julialang.org/t/why-is-there-a-performance-difference-between-global-and-local-variables-in-non-interactive-julia-programs/5753)):

> A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.

However, if you fix the type (like `n_T::Int = 100`), this is no longer a problem. This was introduced in Julia 1.8 ([Types · The Julia Language](https://docs.julialang.org/en/v1/manual/types/#Type-Declarations)):

> As of Julia 1.8, type declarations can now be used in global scope i.e. type annotations can be added to global variables to make accessing them type stable.

---

_[View the full topic](https://discourse.julialang.org/t/for-loop-with-variable-range-so-slow/136149)._
