在一些 Julia 代码中,我们可以看到条件表达式的使用,例如:
if val !== nothing
dosomething()
end
其中val
是类型为Union{Int,Nothing}
的变量。
val !== nothing
和val != nothing
之间有什么区别?
在一些 Julia 代码中,我们可以看到条件表达式的使用,例如:
if val !== nothing
dosomething()
end
其中val
是类型为Union{Int,Nothing}
的变量。
val !== nothing
和val != nothing
之间有什么区别?
首先,通常建议使用 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.
有时候,与===
比较速度比与==
比较要快,因为后者可能涉及类型转换。
===
之所以比==
更快,是因为编译器更容易对其进行推理。此外,在某些情况下,在循环中使用isnothing
将会产生比=== nothing
更低效的代码。参见 https://github.com/JuliaLang/julia/issues/27681。 - Milan Bouchet-Valat===
仍然比isnothing
更快吗?我看到这个问题已经关闭了。 - a06e