Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 Β· Practice and Review

Common Mistakes and Gotchas

The Julia mistakes that cost beginners the most time: slow globals, 1-based indexing, loop order, type instability, aliasing, and Python and MATLAB habits.

Julia is easy to start and easy to write slowly. Most problems people hit in the first months come from a small set of habits: code that works but runs ten times slower than it should, indexes that are off by one, arrays that share memory when you expected a copy, and expectations carried over from Python or MATLAB. This lesson lists them with the symptom, the cause and the fix.

All Julia here is read-only because Julia is not installed on this site. Two Python and NumPy stand-ins let you run the ideas behind memory order and aliasing.

The big five

Slow globals Put hot code in functions.
1-based indexing The first element is v[1].
Loop order Columns are contiguous in memory.
Type instability One variable, many types.
1 / 2

Mistake 1: Doing the work in global scope

Symptom: a loop that should take milliseconds takes seconds.

JULIA
total = 0
for i in 1:10_000_000
    global total += i * 2
end

Variables at the top level of a script can change type at any moment, so the compiler cannot assume anything about total and generates slow, generic code. The same loop in a function is compiled for the concrete types it sees:

JULIA
function total_of(n)
    total = 0
    for i in 1:n
        total += i * 2
    end
    total
end

total_of(10_000_000)   # 100000010000000

Rules of thumb: put computation in functions and pass data as arguments. If you need a global constant, declare it const, as in const RATE = 0.05, so its type is fixed. Never time code at the top level of the REPL and conclude something about Julia's speed. See Performance Tips.

Mistake 2: Forgetting indexing starts at 1

Symptom: BoundsError: attempt to access 3-element Vector{Int64} at index [0].

JULIA
v = [10, 20, 30]
v[1]      # 10
v[end]    # 30
v[0]      # BoundsError

Python and C programmers write for i in 0:n-1. In Julia, the loop is 1:n, or better, eachindex(v), which also works for arrays with unusual index ranges. Another off-by-one source is that ranges and slices include both ends: v[1:2] has two elements and 1:3 includes 3. Python's range(1, 3) stops before 3.

Mistake 3: Looping across rows in the inner loop

Symptom: a matrix loop runs several times slower than the same loop with the indexes swapped.

JULIA
# slower: the inner loop jumps between columns
for i in axes(A, 1), j in axes(A, 2)
    s += A[i, j]
end

# faster: the inner loop walks down a column
for j in axes(A, 2), i in axes(A, 1)
    s += A[i, j]
end

Julia matrices are stored column-major, like Fortran and MATLAB, and unlike NumPy's default of row-major. In a nested for i..., j... loop the last variable changes fastest, so put the first index there. This is the same order that the standard library uses internally. The first stand-in below makes the memory order visible.

Python Column-major versus row-major

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For the column-major array the memory order is 1, 2, 3, 4, 5, 6: walking down a column (first index) moves 8 bytes, one Int64. In the row-major copy, walking down a column jumps 24 bytes. In Julia the first-index-fastest loop therefore touches neighbors in memory and the cache works for you.

Mistake 4: Type instability

Symptom: code that "looks" fast allocates a lot and runs slowly.

JULIA
function bad_sum(v)
    s = 0            # Int
    for x in v
        s += x       # becomes Float64 when v holds floats
    end
    s
end

Here s starts as an Int and becomes a Float64 after the first addition on a float vector, so the compiler must handle both. The fix is to start with a zero of the right type:

JULIA
function good_sum(v)
    s = zero(eltype(v))
    for x in v
        s += x
    end
    s
end

Detect problems with @code_warntype good_sum([1.0, 2.0]); red Union or Any types in the output are the warning sign. Other common causes: returning different types from branches, containers with abstract element types such as Vector{Any} or Vector{Number}, and struct fields without a type annotation (use x::Float64 or a type parameter). More in How Julia Compiles Code.

Mistake 5: Aliasing instead of copying

Symptom: changing one variable changes another.

JULIA
a = [1, 2, 3]
b = a            # b is the same array, not a copy
b[1] = 99
a                # [99, 2, 3]

c = copy(a)      # an independent array

Assignment never copies arrays. Slices on the right-hand side such as a[1:2] do copy, while @view a[1:2] does not. Two traps that look similar:

JULIA
rows = fill([], 3)          # three references to the SAME empty vector
push!(rows[1], 1)
rows                        # [[1], [1], [1]]

rows = [[] for _ in 1:3]    # three different vectors

Mutable structs behave the same way: p2 = p1 shares one object. MATLAB users in particular expect copy-on-assignment semantics; Julia does not provide them. The second stand-in shows the same behavior in Python and NumPy.

Python Aliases, copies and views

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note the one place where NumPy and Julia disagree: a NumPy slice is a view, while a Julia slice x[2:3] is a copy. In Julia you opt in to the view with @view or @views.

Mistake 6: Forgetting the dot

Symptom: MethodError: no method matching sqrt(::Vector{Int64}).

JULIA
v = [1, 4, 9]
sqrt(v)       # MethodError
sqrt.(v)      # [1.0, 2.0, 3.0]
v + 1         # MethodError: use v .+ 1
v .+ 1        # [2, 5, 10]

Julia does not silently vectorize functions the way NumPy does. You ask for element-wise application with a dot. Operators have dotted versions too: .+, .*, .^. Without dots, * on two matrices is a real matrix product, as in MATLAB, not an element-wise product. See Broadcasting and the Dot Syntax.

Mistake 7: Silent integer overflow

Symptom: a huge result suddenly turns negative.

JULIA
typemax(Int64)        # 9223372036854775807
typemax(Int64) + 1    # -9223372036854775808
factorial(21)         # OverflowError: 21 is too large to look up in the table
factorial(big(21))    # 51090942171709440000

Plain integers wrap around with no error. If your numbers can exceed about 9.2 Γ— 10^18, use BigInt (big(21)) or floating-point. The same wraparound makes 2^64 evaluate to 0, which surprises Python users; use big(2)^64 or 2.0^64.

Mistake 8: Soft-scope surprises in scripts

Symptom: a script fails with UndefVarError on a variable you defined above the loop.

JULIA
count = 0
for line in lines
    count += 1      # in a script file this does not update the global count
end

In the REPL, this "soft scope" case is forgiven and updates the global. In a script file, the loop body has its own scope, so count += 1 refers to a new local variable and Julia warns about the ambiguity and then fails. The fix is to wrap the code in a function, or, if you truly want the global, write global count += 1. Scope rules are in Modules and Scope.

Mistake 9: Mixing up characters, strings and byte indexes

JULIA
"a"      # a String
'a'      # a Char
s = "naΓ―ve"
s[3]     # 'Γ―'
s[4]     # StringIndexError: invalid index [4], valid nearby indices [3]/[5]
length(s)   # 5 characters, while sizeof(s) is 6 bytes

String indexes are byte positions into UTF-8 text. Use collect(s), eachindex(s) or first(s, 3) when you need characters, and * (not +) to join strings: "a" * "b". See Strings and Characters.

Comparing with Python and MATLAB habits

Habit from What you write there What to write in Julia
Python x ** 2 x ^ 2
Python x // y and x % y x Γ· y (or div) and x % y (the remainder, sign of x) or mod(x, y) (sign of y)
Python a[0] and a[-1] a[1] and a[end]
Python a[1:3] takes 2 items a[1:3] takes 3 items
Python "a" + "b" "a" * "b" or string("a", "b")
Python if x: (truthy values) if x needs a real Bool; write !isempty(x)
Python None nothing (and missing for absent data)
MATLAB A(1,2) A[1, 2]
MATLAB A * B is a matrix product the same; use .* for element-wise
MATLAB 1:3 is a row vector 1:3 is a range; [1, 2, 3] is a 1-D vector (use [1 2 3] for a 1Γ—3 row)
MATLAB end closes blocks only end also means "last index" inside [...]
MATLAB assignment copies assignment shares arrays; use copy

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why is a loop at the top level of a script usually slower than the same loop in a function?

    The compiler can only generate fast code when it knows concrete types. Non-constant globals could change type at any time, so code that uses them stays generic.
  2. 2. After a = [1, 2, 3]; b = a; b[1] = 99, what is a?

    Assignment binds a second name to the same array. Use copy(a) for an independent copy.
  3. 3. Which loop order is fastest for a Julia matrix A?

    Matrices are stored column by column, so the inner loop should run over the first index to read neighboring memory.
  4. 4. What does typemax(Int64) + 1 give?

    Fixed-width integers wrap around without any error. Use big for arbitrarily large values.

Summary

  • Put hot code in functions; make globals const or pass them as arguments.
  • Indexing starts at 1, ranges include both ends, and end means the last index.
  • Loop with the first index innermost, because matrices are column-major.
  • Keep variables and return values the same type (zero(eltype(v))) and check with @code_warntype.
  • Assignment aliases, copy copies, slices copy, @view shares.
  • Use dots for element-wise work, * to join strings, and big when integers can overflow.

Next: turn these lessons into answers in Julia Interview Questions.