使用 try-catch
块来处理 ArrayIndexOutOfBoundsException
异常可能不是最佳实践,因为异常处理通常比条件检查要慢。
for (idx in move.indices step 2) {
try {
x = p.first + move[idx]
y = p.second + move[idx + 1]
pointNearby = markedImageMatrix[x][y]
if (pointNearby.mark == itm.key) {
bounds[itm.key]?.add(Point(x, y))
}
} catch (e: ArrayIndexOutOfBoundsException) {
continue
}
}
}
使用 if
语句来检查数组边界通常更为高效,因为它避免了异常的生成和处理过程。使用 if
语句进行边界检查的改进版本:
for (idx in move.indices step 2) {
x = p.first + move[idx]
y = p.second + move[idx + 1]
if (x >= 0 && x < markedImageMatrix.size && y >= 0 && y < markedImageMatrix[x].size) {
pointNearby = markedImageMatrix[x][y]
if (pointNearby.mark == itm.key) {
bounds[itm.key]?.add(Point(x, y))
}
}
}
这种方法首先检查 x
和 y
是否在有效的数组索引范围内,只有在索引有效的情况下才尝试访问数组元素。这样可以避免抛出和捕获异常,从而提高代码的效率。同时,这种方法的代码可读性也更好,更容易维护和理解。