使用!==或!=将Julia变量与“ nothing”进行比较

scl*_*cls 0 comparison nothing julia

在一些Julia代码中何时可以看到条件表达式,例如

if val !== nothing
    dosomething()
end
Run Code Online (Sandbox Code Playgroud)

val类型变量在哪里Union{Int,Nothing}

条件val !== nothing和之间有什么区别val != nothing

crs*_*nbr 5

首先,通常建议使用isnothing进行比较nothing。此特定功能非常有效,因为它仅基于类型(@edit isnothing(nothing)):

isnothing(::Any) = false
isnothing(::Nothing) = true
Run Code Online (Sandbox Code Playgroud)

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

关于您的问题,和之间(和等于和)之间的区别在于===,前者检查两件事是否相同,而后者检查是否相等。为了说明这种差异,请考虑以下示例:==!==!=

julia> 1 == 1.0 # equal
true

julia> 1 === 1.0 # but not identical
false
Run Code Online (Sandbox Code Playgroud)

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

两件事完全相同意味着什么?我们可以参考比较运算符(?===)的文档:

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.
Run Code Online (Sandbox Code Playgroud)

有时,与进行比较===要比与进行比较快,==因为后者可能涉及类型转换。

  • `===` 也可以更快,因为编译器比 `==` 更容易推理它。目前,在某些情况下,“isnothing”在循环中给出的代码效率低于“=== Nothing”。请参阅https://github.com/JuliaLang/julia/issues/27681 (4认同)
  • 事实上,性能差异现在应该得到解决。 (3认同)