基于带条件的IO操作的常量变量初始化
Constant variable initialization based on IO operation with a condition
我一直在用 kotlin 编写一些 opencv 应用程序,并根据下面的代码偶然发现了一个我很好奇的问题:
val image =
if (!Imgcodecs.imread(filename).empty())
Imgcodecs.imread(filename)
else
Mat.eye(512, 512, CvType.CV_8U).mul(Mat(512, 512, CvType.CV_8U, Scalar(255.0)))
编译器(通常)是否优化了像这些连续调用(imreads)这样的 IO 操作?
有哪些行之有效的和/或优雅的方法来处理此类问题?
我认为编译器无法知道任意方法是 side-effect 自由的。事实上,这不是(我假设)- 这里可能存在竞争条件。
避免这种情况的一种方法是使用这样的东西:
val image = with(Imgcodecs.imread(filename)) {
if (!empty()) {
this
} else {
Mat.eye(...)
}
}
或者更明确一点的东西,从而避免了 with
idiom:
的魔力
val image = {
val mtx = Imgcodecs.imread(filename)
if (!mtx.empty()) {
mtx
} else {
Mat.eye(...)
}
}
我一直在用 kotlin 编写一些 opencv 应用程序,并根据下面的代码偶然发现了一个我很好奇的问题:
val image =
if (!Imgcodecs.imread(filename).empty())
Imgcodecs.imread(filename)
else
Mat.eye(512, 512, CvType.CV_8U).mul(Mat(512, 512, CvType.CV_8U, Scalar(255.0)))
编译器(通常)是否优化了像这些连续调用(imreads)这样的 IO 操作?
有哪些行之有效的和/或优雅的方法来处理此类问题?
我认为编译器无法知道任意方法是 side-effect 自由的。事实上,这不是(我假设)- 这里可能存在竞争条件。
避免这种情况的一种方法是使用这样的东西:
val image = with(Imgcodecs.imread(filename)) {
if (!empty()) {
this
} else {
Mat.eye(...)
}
}
或者更明确一点的东西,从而避免了 with
idiom:
val image = {
val mtx = Imgcodecs.imread(filename)
if (!mtx.empty()) {
mtx
} else {
Mat.eye(...)
}
}