Creating an array

Hello,
Which of the following methods is best for creating an array?

Array1 = fill(0,100)
Array2 = Array{Int64}(undef,100)

Thank you.

The top one is slower because it fills with zeros, the bottom one is faster because it only allocates memory.

julia> @btime Array1 = fill(0,100)
  30.242 ns (1 allocation: 896 bytes)
julia> @btime Array2 = Array{Int64}(undef,100)
  13.413 ns (1 allocation: 896 bytes)

If you don’t need the 0s, consider the latter.

4 Likes

Hi,
Thank you so much.

1 Like

“Best” depends on your needs.

zeros creates an array with predictable contents.

Array{T}(undef, n) creates an uninitialized array, so that you have to make sure to initialize the elements before using them.

I’d recommend to at least start with the former in most cases as using uninitialized values is a way to heisenbugs. Zeros will at least give predictably wrong answers.

7 Likes

I would very much turn that around and say “If you don’t need the performance, consider the former” (or, consider zeros for a cleaner syntax).

Uninitialized memory is often a nasty source of bugs and you should be very careful when using it.

9 Likes