0% found this document useful (0 votes)
94 views17 pages

The Fast Track To Julia

Julia is an open-source, high-performance programming language for technical computing that can match the speed of C and FORTRAN. It is dynamically typed, supports multiple dispatch, and is designed for parallelism. Julia has a built-in package manager and many built-in mathematical functions. It allows automating code generation through Lisp-inspired macros.

Uploaded by

Eduardo Santiago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views17 pages

The Fast Track To Julia

Julia is an open-source, high-performance programming language for technical computing that can match the speed of C and FORTRAN. It is dynamically typed, supports multiple dispatch, and is designed for parallelism. Julia has a built-in package manager and many built-in mathematical functions. It allows automating code generation through Lisp-inspired macros.

Uploaded by

Eduardo Santiago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

The Fast Track to Julia 15/09/2019 21(17

https://juliadocs.github.io/Julia-Cheat-Sheet/

English The Fast Track to


A quick and dirty overview of 1.0
This page's source is located here . Pull requests are welcome!

What is…?

Julia is an open-source, multi-platform, high-level, high-performance


programming language for technical computing.
Julia has an LLVM-based JIT compiler that allows it to match the
performance of languages such as C and FORTRAN without the hassle of
low-level code. Because the code is compiled on the !y you can run (bits
of) code in a shell or REPL , which is part of the recommended work!ow .
Julia is dynamically typed, provides multiple dispatch , and is designed for
parallelism and distributed computation.
Julia has a built-in package manager.
Julia has many built-in mathematical functions, including special functions
(e.g. Gamma), and supports complex numbers right out of the box.
Julia allows you to generate code automagically thanks to Lisp-inspired
macros.
Julia was born in 2012.

Basics

answer = 42
Assignment x, y, z = 1, [1:10; ], "A string"
x, y = y, x # swap x and y
Constant declaration const DATE_OF_BIRTH = 2012
End-of-line comment i = 1 # This is a comment
Delimited comment #= This is another comment =#
x = y = z = 1 # right-to-left
Chaining 0 < x < 3 # true
5 < x != y < 5 # false
function add_one(i)
Function de"nition return i + 1
end
Insert LaTeX symbols \delta + [Tab]

Operators

Basic arithmetic +, -,*,/


https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 1 de 17
The Fast Track to Julia 15/09/2019 21(17

Basic arithmetic +, -,*,/


Exponentiation 2^3 == 8
Division 3/12 == 0.25
Inverse division 7\3 == 3/7
Remainder x % y or rem(x,y)
Negation !true == false
Equality a == b
Inequality a != b or a ≠ b
Less and larger than < and >
Less than or equal to <= or ≤
Greater than or equal to >= or ≥
[1, 2, 3] .+ [1, 2, 3] == [2, 4, 6]
Element-wise operation
[1, 2, 3] .* [1, 2, 3] == [1, 4, 9]
Not a number isnan(NaN) not(!) NaN == NaN
Ternary operator a == b ? "Equal" : "Not equal"
Short-circuited AND and OR a && b and a || b
Object equivalence a === b

The shell a.k.a. REPL

Recall last result ans


Interrupt execution [Ctrl] + [C]
Clear screen [Ctrl] + [L]
Run program include("filename.jl")
Get help for func is de"ned ?func
See all places where func is de"ned apropos("func")
Command line mode ;
Package Manager mode ]
Help mode ?
Exit special mode / Return to REPL [Backspace] on empty line
Exit REPL exit() or [Ctrl] + [D]

Standard libraries

To help Julia load faster, many core functionalities exist in standard


libraries that come bundled with Julia. To make their functions available,
use using PackageName. Here are some Standard Libraries and popular
functions.

Random rand, randn, randsubseq


Statistics mean, std, cor, median, quantile
LinearAlgebra I, eigvals, eigvecs, det, cholesky
SparseArrays sparse, SparseVector, SparseMatrixCSC
Distributed @distributed, pmap, addprocs
Dates DateTime, Date
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 2 de 17
The Fast Track to Julia 15/09/2019 21(17

Dates DateTime, Date

Package management

Packages must be registered before they are visible to the package


manager. In Julia 1.0, there are two ways to work with the package
manager: either with using Pkg and using Pkg functions, or by typing ] in
the REPL to enter the special interactive package management mode. (To
return to regular REPL, just hit BACKSPACE on an empty line in package
management mode). Note that new tools arrive in interactive mode "rst,
then usually also become available in regular Julia sessions through Pkg
module.
Using Pkg in Julia session

List installed packages (human-readable) Pkg.status()


List installed packages (machine-readable) Pkg.installed()
Update all packages Pkg.update()
Install PackageName Pkg.add("PackageName")
Rebuild PackageName Pkg.build("PackageName")
Use PackageName (after install) using PackageName
Remove PackageName Pkg.rm("PackageName")
In Interactive Package Mode

Add PackageName add PackageName


Remove PackageName rm PackageName
Update PackageName update PackageName
dev PackageName or
Use development version dev GitRepoUrl
Stop using development version, revert to free PackageName
public release

Characters and strings

Character chr = 'C'


String str = "A string"
Character code Int('J') == 74
Character from code Char(74) == 'J'
chr = '\uXXXX' # 4-digit HEX
Any UTF character chr = '\UXXXXXXXX' # 8-digit HEX
for c in str
Loop through characters println(c)
end
Concatenation str = "Learn" * " " * "Julia"
a = b = 2
String interpolation
println("a * b = $(a*b)")
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 3 de 17
The Fast Track to Julia 15/09/2019 21(17

First matching character or regular findfirst(isequal('i'), "Julia")


expression == 4
Replace substring or regular replace("Julia", "a" => "us") ==
expression "Julius"
Last index (of collection) lastindex("Hello") == 5
Number of characters length("Hello") == 5
Regular expression pattern = r"l[aeiou]"
str = "+1 234 567 890"
pat = r"\+([0-9]) ([0-9]+)"
Subexpressions m = match(pat, str)
m.captures == ["1", "234"]
[m.match for m = eachmatch(pat,
All occurrences str)]
All occurrences (as iterator) eachmatch(pat, str)
Beware of multi-byte Unicode encodings in UTF-8:
10 == lastindex("Ångström") != length("Ångström") == 8
Strings are immutable.

Numbers

IntN and UIntN, with


Integer types
N ∈ {8, 16, 32, 64, 128}, BigInt
FloatN with N ∈ {16, 32, 64}
Floating-point types BigFloat
Minimum and maximum typemin(Int8)
values by type typemax(Int64)
Complex types Complex{T}
Imaginary unit im
Machine precision eps() # same as eps(Float64)
round() # floating-point
Rounding round(Int, x) # integer
convert(TypeName, val) #
attempt/error
Type conversions typename(val) # calls
convert
pi # 3.1415...
Global constants π # 3.1415...
im # real(im * im) == -1
More constants using Base.MathConstants
Julia does not automatically check for numerical over!ow. Use package
SaferIntegers for ints with over!ow checking.

Random Numbers

Many random number functions require using Random.

https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 4 de 17
The Fast Track to Julia 15/09/2019 21(17

Set seed seed!(seed)


rand() # uniform [0,1)
Random numbers randn() # normal (-Inf,
Inf)
using Distributions
my_dist = Bernoulli(0.2)
Random from Other Distribution # For example
rand(my_dist)
Random subsample elements from A with randsubseq(A, p)
inclusion probability p
Random permutation elements of A shuffle(A)

Arrays

Declaration arr = Float64[]


Pre-allocation sizehint!(arr, 10^4)
arr = Any[1,2]
Access and assignment arr[1] = "Some text"
a = [1:10;]
b = a # b points to a
Comparison a[1] = -99
a == b # true
b = copy(a)
Copy elements (not address) b = deepcopy(a)
Select subarray from m to n arr[m:n]
n-element array with 0.0s zeros(n)
n-element array with 1.0s ones(n)
n-element array with #undefs Vector{Type}(undef,n)
n equally spaced numbers from start range(start,stop=stop,length=n)
to stop
Array with n random Int8 elements rand(Int8, n)
Fill array with val fill!(arr, val)
Pop last element pop!(arr)
Pop "rst element popfirst!(a)
Push val as last element push!(arr, val)
Push val as "rst element pushfirst!(arr, val)
Remove element at index idx deleteat!(arr, idx)
Sort sort!(arr)
Append a with b append!(a,b)
Check whether val is element in(val, arr) or val in arr
Scalar product dot(a, b) == sum(a .* b)
reshape(1:6, 3, 2)' == [1 2 3;
Change dimensions (if possible) 4 5 6]
To string (with delimiter del between join(arr, del)
elements)

https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 5 de 17
The Fast Track to Julia 15/09/2019 21(17

Linear Algebra

For most linear algebra tools, use using LinearAlgebra.

I # just use variable I. Will automatically


Identity matrix conform to dimensions required.
De"ne matrix M = [1 0; 0 1]
Matrix dimensions size(M)
Select i th row M[i, :]
Select i th column M[:, i]
Concatenate M = [a b] or M = hcat(a, b)
horizontally
Concatenate M = [a ; b] or M = vcat(a, b)
vertically
Matrix transpose(M)
transposition
Conjugate matrix M' or adjoint(M)
transposition
Matrix trace tr(M)
Matrix det(M)
determinant
Matrix rank rank(M)
Matrix eigenvalues eigvals(M)
Matrix eigvecs(M)
eigenvectors
Matrix inverse inv(M)
Solve M*x == v M\v is better than inv(M)*v
Moore-Penrose pinv(M)
pseudo-inverse
Julia has built-in support for matrix decompositions.
Julia tries to infer whether matrices are of a special type (symmetric,
hermitian, etc.), but sometimes fails. To aid Julia in dispatching the optimal
algorithms, special matrices can be declared to have a structure with
functions like Symmetric , Hermitian , UpperTriangular, LowerTriangular,
Diagonal , and more.

Control flow and loops

Conditional if-elseif-else-end
for i in 1:10
Simple for loop println(i)
end
for i in 1:10, j = 1:5
Unnested for loop println(i*j)
end
for (idx, val) in enumerate(arr)
Enumeration println("the $idx-th element is $val")
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 6 de 17
The Fast Track to Julia 15/09/2019 21(17

Enumeration println("the $idx-th element is $val")


end
while bool_expr
while loop # do stuff
end
Exit loop break
Exit iteration continue

Functions

All arguments to functions are passed by reference.


Functions with ! appended change at least one argument, typically the
"rst: sort!(arr).
Required arguments are separated with a comma and use the positional
notation.
Optional arguments need a default value in the signature, de"ned with =.
Keyword arguments use the named notation and are listed in the
function’s signature after the semicolon:
function func(req1, req2; key1=dflt1, key2=dflt2)
# do stuff
end
The semicolon is not required in the call to a function that accepts keyword
arguments.
The return statement is optional but highly recommended.
Multiple data structures can be returned as a tuple in a single return
statement.
Command line arguments julia script.jl arg1 arg2... can be processed
from global constant ARGS:
for arg in ARGS
println(arg)
end
Anonymous functions can best be used in collection functions or list
comprehensions: x -> x^2.
Functions can accept a variable number of arguments:
function func(a...)
println(a)
end

func(1, 2, [3:5]) # tuple: (1, 2, UnitRange{Int64}[3:5])


Functions can be nested:
function outerfunction()
# do some outer stuff
function innerfunction()
# do inner stuff
# can access prior outer definitions
end
# do more outer stuff
end
Functions can have explicit return types
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 7 de 17
The Fast Track to Julia 15/09/2019 21(17

Functions can have explicit return types


# take any Number subtype and return it as a String
function stringifynumber(num::T)::String where T <: Number
return "$num"
end
Functions can be vectorized by using the Dot Syntax
# here we broadcast the subtraction of each mean value
# by using the dot operator
julia> using Statistics
julia> A = rand(3, 4);
julia> B = A .- mean(A, dims=1)
3×4 Array{Float64,2}:
0.0387438 0.112224 -0.0541478 0.455245
0.000773337 0.250006 0.0140011 -0.289532
-0.0395171 -0.36223 0.0401467 -0.165713
julia> mean(B, dims=1)
1×4 Array{Float64,2}:
-7.40149e-17 7.40149e-17 1.85037e-17 3.70074e-17
Julia generates specialized versions of functions based on data types.
When a function is called with the same argument types again, Julia can
look up the native machine code and skip the compilation process.
Since Julia 0.5 the existence of potential ambiguities is still acceptable,
but actually calling an ambiguous method is an immediate error
error.
Stack over!ow is possible when recursive functions nest many levels deep.
Trampolining can be used to do tail-call optimization, as Julia does not do
that automatically yet. Alternatively, you can rewrite the tail recursion as
an iteration.

Dictionaries

d = Dict(key1 => val1, key2 => val2,


...)
Dictionary d = Dict(:key1 => val1, :key2 => val2,
...)
All keys (iterator) keys(d)
All values (iterator) values(d)
for (k,v) in d
Loop through key-value println("key: $k, value: $v")
pairs end
Check for key :k haskey(d, :k)
Copy keys (or values) to arr = collect(keys(d))
array arr = [k for (k,v) in d]
Dictionaries are mutable; when symbols are used as keys, the keys are
immutable.

Sets

Declaration s = Set([1, 2, 3, "Some text"])


https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 8 de 17
The Fast Track to Julia 15/09/2019 21(17

Declaration s = Set([1, 2, 3, "Some text"])


Union s1 ∪ s2 union(s1, s2)
Intersection s1 ∩ s2 intersect(s1, s2)
Di#erence s1 \\ s2 setdiff(s1, s2)
Di#erence s1 s2 symdiff(s1, s2)
Subset s1 ⊆ s2 issubset(s1, s2)
Checking whether an element is contained in a set is done in O(1).

Collection functions

map(f, coll) or
map(coll) do elem
Apply f to all elements of collection # do stuff with elem
coll
# must contain return
end
Filter coll for true values of f filter(f, coll)
arr = [f(elem) for elem in
List comprehension coll]

Types

Julia has no classes and thus no class-speci"c methods.


Types are like classes without methods.
Abstract types can be subtyped but not instantiated.
Concrete types cannot be subtyped.
By default, struct s are immutable.
Immutable types enhance performance and are thread safe, as they can be
shared among threads without the need for synchronization.
Objects that may be one of a set of types are called Union types.

Type annotation var::TypeName


struct Programmer
name::String
Type declaration birth_year::UInt16
fave_language::AbstractString
end
Mutable type declaration replace struct with mutable struct
Type alias const Nerd = Programmer
Type constructors methods(TypeName)
me = Programmer("Ian", 1984, "Julia")
Type instantiation me = Nerd("Ian", 1984, "Julia")
abstract type Bird end
struct Duck <: Bird
Subtype declaration pond::String
end
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 9 de 17
The Fast Track to Julia 15/09/2019 21(17

end
struct Point{T <: Real}
x::T
y::T
Parametric type
end

p =Point{Float64}(1,2)
Union types Union{Int, String}
Traverse type hierarchy supertype(TypeName) and subtypes(TypeName)
Default supertype Any
All "elds fieldnames(TypeName)
All "eld types TypeName.types
When a type is de"ned with an inner constructor, the default outer
constructors are not available and have to be de"ned manually if need be.
An inner constructor is best used to check whether the parameters
conform to certain (invariance) conditions. Obviously, these invariants can
be violated by accessing and modifying the "elds directly, unless the type
is de"ned as immutable. The new keyword may be used to create an object
of the same type.
Type parameters are invariant, which means that
Point{Float64} <: Point{Real} is false, even though Float64 <: Real.
Tuple types, on the other hand, are covariant:
Tuple{Float64} <: Tuple{Real}.
The type-inferred form of Julia’s internal representation can be found with
code_typed(). This is useful to identify where Any rather than type-speci"c
native code is generated.

Missing and Nothing

Programmers Null nothing


Missing Data missing
Not a Number in NaN
Float
collect(skipmissing([1, 2, missing])) ==
Filter missings [1,2]
Replace missings collect((df[:col], 1))
Check if missing ismissing(x) not x == missing

Exceptions

Throw throw(SomeExcep())
SomeExcep
Rethrow current rethrow()
exception
struct NewExcep <: Exception
v::String
end
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 10 de 17
The Fast Track to Julia 15/09/2019 21(17

end
De"ne NewExcep Base.showerror(io::IO, e::NewExcep) = print(io,
"A problem with $(e.v)!")

throw(NewExcep("x"))
Throw error with error(msg)
msg text
try
# do something potentially iffy
catch ex
if isa(ex, SomeExcep)
# handle SomeExcep
elseif isa(ex, AnotherExcep)
Handler # handle AnotherExcep
else
# handle all others
end
finally
# do this in any case
end

Modules

Modules are separate global variable workspaces that group together


similar functionality.

module PackageName
# add module definitions
De"nition # use export to make definitions accessible
end
Include
filename.jl include("filename.jl")
using ModuleName # all exported names
using ModuleName: x, y # only x, y
using ModuleName.x, ModuleName.y: # only x, y
Load import ModuleName # only ModuleName
import ModuleName: x, y # only x, y
import ModuleName.x, ModuleName.y # only x, y
# Get an array of names exported by Module
names(ModuleName)

# include non-exports, deprecateds


# and compiler-generated names
Exports names(ModuleName, all::Bool)
#also show namesexplicitely imported from other
modules
names(ModuleName, all::Bool, imported::Bool)
There is only one di#erence between using and import : with using you
need to say function Foo.bar(.. to extend module Foo’s function bar with
a new method, but with import Foo.bar, you only need to say
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 11 de 17
The Fast Track to Julia 15/09/2019 21(17

a new method, but with import Foo.bar, you only need to say
function bar(... and it automatically extends module Foo’s function bar .

Expressions

Julia is homoiconic: programs are represented as data structures of the


language itself. In fact, everything is an expression Expr.
Symbols are interned strings pre"xed with a colon. Symbols are more
e$cient and they are typically used as identi"ers, keys (in dictionaries), or
columns in data frames. Symbols cannot be concatenated.
Quoting :( ... ) or quote ... end creates an expression, just like
parse(str) , and Expr(:call, ...).
x = 1
line = "1 + $x" # some code
expr = parse(line) # make an Expr object
typeof(expr) == Expr # true
dump(expr) # generate abstract syntax tree
eval(expr) == 2 # evaluate Expr object: true

Macros

Macros allow generated code (i.e. expressions) to be included in a program.

macro macroname(expr)
De"nition # do stuff
end
Usage macroname(ex1, ex2, ...) or @macroname ex1, ex2, ...
@test # equal (exact)
@test_approx_eq # equal (modulo numerical errors)
@test x ≈ y # isapprox(x, y)
@assert # assert (unit test)
@which # types used
@time # time and memory statistics
@elapsed # time elapsed
Built-in macros @allocated # memory allocated
@profile # profile
@spawn # run at some worker
@spawnat # run at specified worker
@async # asynchronous task
@distributed # parallel for loop
@everywhere # make available to workers
Rules for creating hygienic macros:
Declare variables inside macro with local .
Do not call eval inside macro.
Escape interpolated expressions to avoid expansion: $(esc(expr))

Parallel Computing

https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 12 de 17
The Fast Track to Julia 15/09/2019 21(17

Parallel computing tools are available in the Distributed standard library.

Launch REPL with N workers julia -p N


Number of available workers nprocs()
Add N workers addprocs(N)
for pid in workers()
See all worker ids println(pid)
end
Get id of executing worker myid()
Remove worker rmprocs(pid)
r = remotecall(f, pid, args...)
# or:
Run f with arguments args on r = @spawnat pid f(args)
pid
...
fetch(r)
Run f with arguments args on remotecall_fetch(f, pid, args...)
pid (more e$cient)
Run f with arguments args on r = @spawn f(args) ... fetch(r)
any worker
Run f with arguments args on r = [@spawnat w f(args) for w in
all workers workers()] ... fetch(r)
Make expr available to all @everywhere expr
workers
sum = @distributed (red) for i in
Parallel for loop with reducer 1:10^6
function red # do parallelstuff
end
Apply f to all elements in pmap(f, coll)
collection coll
Workers are also known as concurrent/parallel processes.
Modules with parallel processing capabilities are best split into a functions
"le that contains all the functions and variables needed by all workers, and
a driver "le that handles the processing of data. The driver "le obviously
has to import the functions "le.
A non-trivial (word count) example of a reducer function is provided by
Adam DeConinck.

I/O

stream = stdin
for line in eachline(stream)
Read stream
# do stuff
end
open(filename) do file
for line in eachline(file)
Read "le # do stuff
end
end
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 13 de 17
The Fast Track to Julia 15/09/2019 21(17

end
using CSV
Read CSV "le data = CSV.read(filename)
using CSV
Write CSV "le CSV.write(filename, data)
using JLD
Save Julia Object save(filename, "object_key", object, ...)
using JLD
Load Julia Object d = load(filename) # Returns a dict of objects
using HDF5
Save HDF5 h5write(filename, "key", object)
using HDF5
Load HDF5 h5read(filename, "key")

DataFrames

For dplyr-like tools, see DataFramesMeta.jl.

Read Stata, SPSS, etc. StatFiles Package


Describe data frame describe(df)
Make vector of column col v = df[:col]
Sort by col sort!(df, [:col])
Categorical col categorical!(df, [:col])
List col levels levels(df[:col])
All observations with col==val df[df[:col] .== val, :]
stack(df, [1:n; ])
Reshape from wide to long stack(df, [:col1, :col2, ...]
format
melt(df, [:col1, :col2]) [
Reshape from long to wide unstack(df, :id, :val)
format
allowmissing!(df) or
Make Nullable allowmissing!(df, :col)
for r in eachrow(df)
# do stuff.
Loop over Rows # r is Struct with fields of col
names.
end
for c in eachcol(df)
# do stuff.
Loop over Columns # c is tuple with name, then
vector
end
Apply func to groups by(df, :group_col, func)
using Query
query = @from r in df begin
@where r.col1 > 40
Query @select {new_name=r.col1, r.col2}
@collect DataFrame # Default:
iterator
end
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 14 de 17
The Fast Track to Julia 15/09/2019 21(17

end

Introspection and reflection

Type typeof(name)
Type check isa(name, TypeName)
List subtypes subtypes(TypeName)
List supertype supertype(TypeName)
Function methods methods(func)
JIT bytecode code_llvm(expr)
Assembly code code_native(expr)

Noteworthy packages and projects

Many core packages are managed by communities with names of the form
Julia[Topic].

Statistics JuliaStats
Di#erential Equations JuliaDi#Eq (Di#erentialEquations.jl)
Automatic di#erentiation JuliaDi#
Numerical optimization JuliaOpt
Plotting JuliaPlots
Network (Graph) Analysis JuliaGraphs
Web JuliaWeb
Geo-Spatial JuliaGeo
Machine Learning JuliaML
DataFrames # linear/logistic regression
Distributions # Statistical distributions
Flux # Machine learning
Super-used Packages Gadfly # ggplot2-likeplotting
LightGraphs # Network analysis
TextAnalysis # NLP

Naming Conventions

The main convention in Julia is to avoid underscores unless they are


required for legibility.
Variable names are in lower (or snake) case: somevariable.
Constants are in upper case: SOMECONSTANT.
Functions are in lower (or snake) case: somefunction.
Macros are in lower (or snake) case: @somemacro.
Type names are in initial-capital camel case: SomeType.
Julia "les have the jl extension.
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 15 de 17
The Fast Track to Julia 15/09/2019 21(17

Julia "les have the jl extension.


For more information on Julia code style visit the manual: style guide .

Performance tips

Avoid global variables.


Write type-stable code.
Use immutable types where possible.
Use sizehint! for large arrays.
Free up memory for large arrays with arr = nothing.
Access arrays along columns, because multi-dimensional arrays are
stored in column-major order.
Pre-allocate resultant data structures.
Disable the garbage collector in real-time applications: disable_gc().
Avoid the splat (...) operator for keyword arguments.
Use mutating APIs (i.e. functions with ! to avoid copying data structures.
Use array (element-wise) operations instead of list comprehensions.
Avoid try-catch in (computation-intensive) loops.
Avoid Any in collections.
Avoid abstract types in collections.
Avoid string interpolation in I/O.
Vectorizing does not improve speed (unlike R, MATLAB or Python).
Avoid eval at run-time.

IDEs, Editors and Plug-ins

Juno (editor)
JuliaBox (online IJulia notebook)
Jupyter (online IJulia notebook)
Emacs Julia mode (editor)
vim Julia mode (editor)
VS Code extension (editor)

Resources

O$cial documentation .
Learning Julia page.
Month of Julia
Community standards .
Julia: A fresh approach to numerical computing (pdf)
Julia: A Fast Dynamic Language for Technical Computing (pdf)

Videos

The 5th annual JuliaCon 2018


The 4th annual JuliaCon 2017 (Berkeley)
The 3rd annual JuliaCon 2016
Getting Started with Julia by Leah Hanson
Intro to Julia by Huda Nassar
Introduction to Julia for Pythonistas by John Pearson
https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 16 de 17
The Fast Track to Julia 15/09/2019 21(17

Introduction to Julia for Pythonistas by John Pearson


Country !ag icons made by Freepik from www.!aticon.com is licensed by CC 3.0 BY.

https://juliadocs.github.io/Julia-Cheat-Sheet/ Página 17 de 17

You might also like