6

How can I check if a string is empty?

I am currently using the == operator:

julia> x = "";

julia> x == "";
true
1
  • if (strlen(x)==0) {}
    – user12211554
    Commented Jan 22, 2020 at 22:55

1 Answer 1

13

Use isempty. It is more explicit and more likely to be optimized for its use case.

For example, on the latest Julia:

julia> using BenchmarkTools

julia> myisempty(x::String) = x == ""
foo (generic function with 1 method)

julia> @btime myisempty("")
  2.732 ns (0 allocations: 0 bytes)
true

julia> @btime myisempty("bar")
  3.001 ns (0 allocations: 0 bytes)
false

julia> @btime isempty("")
  1.694 ns (0 allocations: 0 bytes)
true

julia> @btime isempty("bar")
  1.594 ns (0 allocations: 0 bytes)
false
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.