Bounds checking is well-known to be slow. Early CPU's even had a special function for it, so much of a performance impact does it cause. Even today, C++ defines std::vector::at
to do bounds checking, and leaves the ordinary vector::operator[]
unchecked.
This makes sense. Most of the critical use of operator[]
is in loops, and there you only need to check the loop boundaries. The whole middle of the loop is safe.
C++ has further ways to make loops safe. Idioms like for (element:collection)
don't force you to write the bounds, so you can't get it wrong either.
As a minor optimization, C++20 allows
if ( i < -nghost || i >= cols_x+nghost ||
j < -nghost || j >= rows_y+nghost )
{
[[unlikely]]
std::cout << "Index out of bounds. Exiting.
";
exit(EXIT_FAILURE);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…