Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Julia Performance Tips

Julia Performance Tips

Julia's performance comes from type inference and JIT compilation: the compiler needs to know the type of every value to generate efficient code. Therefore almost all Julia performance problems stem from "the compiler cannot guess the type"; once you grasp this, writing code close to C speed is not hard.


Put Performance-Critical Code in Functions

Any performance-critical code should be placed inside a function. Code inside a function is compiled and optimized, while top-level (global scope) code runs much slower:

Example

Bad: a loop written at the top level of a script is very slow

for

i

in

1

:

1

_000_000

    x += sin

(

i

)

   

Slow

end

Good: wrap it in a function

function

mysum

(

n

)

    x =

0.0

   

for

i

in

1

:n

        x += sin

(

i

)

   

fast

   

end

   

return

x

end

Avoid Non-const Global Variables

The value (and type) of a global variable can change at any time, so the compiler cannot optimize code that uses it. Solutions: either pass it to the function as an argument, or declare it const:

Example

Bad: the function uses a global variable directly

julia

x = rand

(

1000

)

;

julia

function

sum_global

(

)

           s =

0.0

           

for

i

in

x          

x is a global variable, slow

               s += i

           

end

           

return

s

       

end

The first call includes compilation time; look at the second

julia

@

time

sum_global

(

)

 

0.000091

seconds

(

3.49

k allocations:

70.156

KiB

)

     

Lots of extra allocations

Good: pass x in as an argument

julia

function

sum_arg

(

x

)

           s =

0.0

           

for

i

in

x

               s += i

           

end

           

return

s

       

end

julia

@

time

sum_arg

(

x

)

 

0.000006

seconds

(

1

allocation:

16

bytes

)

             

Zero allocations, 15 times faster

If a global variable truly is indispensable, add a const declaration:

const DEFAULT_VAL = 0


Measuring Performance: @time

Use the @time macro to measure execution time, focusing onmemory allocation. The first call includes compilation time, so look at the second result:

Example

julia

@

time

my_function

(

)

 

0.000091

seconds

(

3.49

k allocations:

70.156

KiB

)

@btime (BenchmarkTools package) is more professional and samples automatically many times

julia

using

BenchmarkTools

julia

@btime my_function

(

)

 

1.083

μs

(

0

allocations:

0

bytes

)

Fewer allocations is better. Purely numerical computation (such as vector sums) should achieve 0 allocation. Unexpected large allocations usually mean type instability.

Type Stability

Type stabilitymeans the return type of a function is determined only by the argument types, independent of the values. This is the first principle of high-performance Julia:

Example

Bad: the return type depends on the value of x (may return Int or Float64)

julia

pos

(

x

)

= x

<

0

?

0

: x

pos

(

generic

function

with

1

method

)

Good: zero(x) guarantees the return value has the same type as x

julia

pos

(

x

)

= x

<

0

?

zero

(

x

)

: x

pos

(

generic

function

with

1

method

)

Changing a variable's type inside a loop is equally harmful:

Example

Bad: x is Int first and becomes Float64 after the first iteration

julia

function

foo

(

)

           x =

1

           

for

i =

1

:

10

               x /= rand

(

)

           

end

           

return

x

       

end

Good: initialize as Float64 so the type stays the same throughout

julia

function

foo

(

)

           x =

1.0

           

for

i =

1

:

10

               x /= rand

(

)

           

end

           

return

x

       

end

Check Types with @code_warntype

@code_warntype shows the types inferred by the compiler; the red (non-concrete type) parts are the problem:

Example

julia

@code_warntype pos

(

1.5

)

MethodInstance

for

pos

(

::

Float64

)

Arguments

  x::

Float64

Locals

  y::

Union

{

Float64

,

Int64

}

     

Union means type instability!

Body::

Float64


Avoid Containers of Abstract Types

Arrays whose element type is abstract perform poorly because each element is a pointer to a heap object:

Example

Bad: the element type is the abstract type Real

julia

a =

Real

[

1

,

2.0

, pi

]

3

-element

Vector

{

Real

}

Good: the elements are all Float64, stored compactly

julia

a =

Float64

[

1

,

2.0

, pi

]

3

-element

Vector

{

Float64

}

:

 

1.0

 

2.0

 

3.141592653589793

Likewise, struct fields should use concrete types where possible; abstract type fields should be replaced with type parameters:

Example

Bad: the field is an abstract type, every access needs dynamic type lookup

julia

struct MyStillAmbiguousType

           a::AbstractFloat

       

end

Good: use a type parameter so each instance has a fixed field type

julia

mutable struct MyType

{

T

<

:AbstractFloat

}

a::T

end

julia

m = MyType

(

3.2

)

     

MyType{Float64}

MyType

{

Float64

}

(

3.2

)

In particular, do not use the abstract Function type when storing a function in a struct field:

Example

Bad

struct BadWrapper

    f::

Function

           

Function is an abstract type

end

Good: F is a type parameter, calling has zero overhead

struct GoodWrapper

{

F

}

    f::F

end


Preallocate Output Arrays

Repeatedly creating arrays inside a loop produces many allocations and GC pressure. Create the output array outside the loop and reuse it:

Example

Bad: every call allocates a new array

julia

function

xinc

(

x

)

           

return

[

x + i

for

i

in

1

:

3000

]

       

end

;

Good: write output into a preallocated array

julia

function

xinc

!

(

ret, x

)

           

for

i

in

1

:

3000

               ret

[

i

]

= x + i

           

end

           nothing

       

end

;

Timing comparison: the preallocated version is 30 times faster

julia

@

time

loopinc

(

)

 

0.297454

seconds

(

200.00

k allocations:

2.239

GiB,

39.80

%

gc

time

)

julia

@

time

loopinc_prealloc

(

)

 

0.009410

seconds

(

2

allocations:

23.477

KiB

)


Array Access Order: Column-Major

Julia arrays are stored incolumn-major(column-major) order, that is, the first column is stored completely before the second. Iterating over the first dimension in the inner loop is fastest:

Column-Major Order Memory Layout Diagram

Example

Good: i is the inner loop, accessing memory in order (column-major)

julia

function

copy_col_row

(

x

)

           out =

similar

(

x

)

           

for

col

in

axes

(

x,

2

)

, row

in

axes

(

x,

1

)

               out

[

row, col

]

= x

[

row, col

]

           

end

           

return

out

       

end

Bad: j is the inner loop, jumping around in memory, much slower

julia

function

copy_row_col

(

x

)

           out =

similar

(

x

)

           

for

row

in

axes

(

x,

1

)

, col

in

axes

(

x,

2

)

               out

[

row, col

]

= x

[

row, col

]

           

end

           

return

out

       

end

Use Views to Avoid Copies

An array slice A[1:5, :] by defaultCopydata. If you only need a slice temporarily, using @views or view() to create a view that references the original array is more efficient:

Example

Copy version: allocates 7.6MB

julia

fcopy

(

x

)

= sum

(

x

[

2

:end-

1

]

)

;

View version: zero copy, 3 times faster

julia

@views fview

(

x

)

= sum

(

x

[

2

:end-

1

]

)

;

julia

x = rand

(

10

^

6

)

;

julia

@

time

fcopy

(

x

)

;

 

0.003051

seconds

(

3

allocations:

7.629

MB

)

julia

@

time

fview

(

x

)

;

 

0.001020

seconds

(

1

allocation:

16

bytes

)


Prefer Fused Dot Syntax

Nested "dot" operations are fused into a single loop and produce no temporary arrays:

Example

Bad: 3A, A.^2. 4A each produces a temporary array

julia

f

(

x

)

= 3x.^

2

3

;

Good: the @. macro adds dots to all operations, fusing everything into one loop

julia

fdot

(

x

)

= @. 3x^

2

3

;

julia

x = rand

(

10

^

6

)

;

julia

@

time

f

(

x

)

;

 

0.019049

seconds

(

16

allocations:

45.777

MiB,

18.59

%

gc

time

)

julia

@

time

fdot

(

x

)

;

 

0.002790

seconds

(

6

allocations:

7.630

MiB

)

In this example fdot is 10 times faster and uses only 1/6 the memory.

Speeding Up Small Arrays: StaticArrays

Arrays of fixed and very small length (fewer than 100 elements) can use the StaticArrays.jl package; the compiler generates fully unrolled code for the concrete size:

Example

julia

using

StaticArrays

SVector: a fixed-length static vector, allocated on the stack

julia

v = @SVector

[

1.0

,

2.0

]

2

-element SVector

{

2

,

Float64

}

with indices SOneTo

(

2

)

:

 

1.0

 

2.0

julia

norm

(

v

)

   

Fully unrolled into a few machine instructions, zero allocations

2.23606797749979


Compilation Latency and Precompilation

Julia's first call includes compilation time (the TTFX problem). Mitigations:

Method Description
PrecompileTools.jl Package authors use it to record typical usage so the code is precompiled automatically when users load it
PackageCompiler.jl Compile the package and dependencies into a custom system image
Reduce dependencies Fewer dependencies mean faster loading; use @time using PackageName to find slow dependencies

Performance Optimization Checklist

Check item Key Points
Is the code inside a function? Performance-critical code must be wrapped in a function
Are there global variables? Change to argument passing, or add const
Is it type stable? Check with @code_warntype and eliminate Union
Are container types concrete? Avoid Vector{Any} and AbstractFloat fields
Are there many allocations? Numerical computation should have zero allocations; preallocate output
Is the loop order right? Column-major: the inner loop walks the first dimension
Should dot syntax be used? Use . fusion for nested array operations
Is the array small and fixed? Consider StaticArrays.jl
Does the slice need a copy? Use @views for temporary slices

Note:Measure before optimizing. Use @time or BenchmarkTools to confirm where the bottleneck is, then make targeted changes, and avoid premature optimization based on intuition.