使用 !== 或 != 比较 Julia 变量和 `nothing`。

11

在一些 Julia 代码中,我们可以看到条件表达式的使用,例如:

if val !== nothing
    dosomething()
end

其中val是类型为Union{Int,Nothing}的变量。

val !== nothingval != nothing之间有什么区别?

1个回答

22

首先,通常建议使用 isnothing 来比较某个东西是否为 nothing。这个特定的函数很高效,因为它仅基于类型(@edit isnothing(nothing)):

isnothing(::Any) = false
isnothing(::Nothing) = true

(请注意,nothing是类型Nothing的唯一实例。)

关于你的问题,=====(同样的,!==!=)之间的区别在于前者检查两个事物是否完全相同,而后者则检查它们是否相等。为了说明这种差异,请考虑以下示例:

julia> 1 == 1.0 # equal
true

julia> 1 === 1.0 # but not identical
false

请注意,前者是整数而后者是浮点数。

当两个事物相同的时候,这意味着什么?我们可以查看比较运算符(?===)的文档:

help?> ===
search: === == !==

  ===(x,y) -> Bool
  ≡(x,y) -> Bool

  Determine whether x and y are identical, in the sense that no program could distinguish them. First the types
  of x and y are compared. If those are identical, mutable objects are compared by address in memory and
  immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes
  called "egal". It always returns a Bool value.
有时候,与===比较速度比与==比较要快,因为后者可能涉及类型转换。

5
=== 之所以比 == 更快,是因为编译器更容易对其进行推理。此外,在某些情况下,在循环中使用 isnothing 将会产生比 === nothing 更低效的代码。参见 https://github.com/JuliaLang/julia/issues/27681。 - Milan Bouchet-Valat
@MilanBouchet-Valat 现在 === 仍然比 isnothing 更快吗?我看到这个问题已经关闭了。 - a06e
2
实际上,性能差异现在应该已经被修复了。 - Milan Bouchet-Valat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接