logo

How to Check if an Array is Empty in Julia 📂Julia

How to Check if an Array is Empty in Julia

Overview

Use the isempty() function.

Code

julia> isempty([])
true

julia> isempty(Set())
true

julia> isempty("")
true

Though it’s mentioned as an array in the title, it actually could be a set or a string.

Optimization

Of course, checking if an array is empty by seeing if length() is $0$ might be fine too.

julia> @time for t in 1:10^6
           isempty([])
       end
  0.039721 seconds (1000.00 k allocations: 76.294 MiB, 27.85% gc time)

julia> @time for t in 1:10^6
           length([]) == 0
       end
  0.041762 seconds (1000.00 k allocations: 76.294 MiB, 19.18% gc time)

As you can see, for an empty array, both methods show no performance difference.

julia> x = 1:10^6;

julia> @time for t in 1:10^6
           isempty(x)
       end
  0.017158 seconds

julia> @time for t in 1:10^6
           length(x) == 0
       end
  0.043243 seconds (1000.00 k allocations: 15.259 MiB)

However, when the array is not empty, like above, you can see more than twice the speed difference. It’s natural that length() has to return the actual length while isempty() only needs to check if the first element exists. Considering aspects like readability or when using in conditional statements, using isempty() is more advisable.

Full Code

isempty([])
isempty(Set())
isempty("")

@time for t in 1:10^6
    isempty([])
end
@time for t in 1:10^6
    length([]) == 0
end

x = 1:10^6
@time for t in 1:10^6
    isempty(x)
end
@time for t in 1:10^6
    length(x) == 0
end

Environment

  • OS: Windows
  • julia: v1.6.3