Browse Source

Optimize CMap::isInTheMap

replace x >= 0 && x < size by (unsigned)x < size

By converting signed coordinate to unsigned number, negative values became
very large positive ones, larger than every positive signed number and
therefore also bigger than the map size. As a result check against size
also implicitly checks if coordinate is negative.

Compiler cannot do this transformation automatically because it doesn't
know that map dimensions are always positive.

The change shrinks isInTheMap from 19 instructions to 11 on x86.
K 1 year ago
parent
commit
3a27725fcb
1 changed files with 5 additions and 1 deletions
  1. 5 1
      lib/mapping/CMap.cpp

+ 5 - 1
lib/mapping/CMap.cpp

@@ -334,7 +334,11 @@ bool CMap::isCoastalTile(const int3 & pos) const
 
 bool CMap::isInTheMap(const int3 & pos) const
 {
-	return pos.x >= 0 && pos.y >= 0 && pos.z >= 0 && pos.x < width && pos.y < height && pos.z <= (twoLevel ? 1 : 0);
+	// Check whether coord < 0 is done implicitly. Negative signed int overflows to unsigned number larger than all signed ints.
+	return
+		static_cast<uint32_t>(pos.x) < static_cast<uint32_t>(width) &&
+		static_cast<uint32_t>(pos.y) < static_cast<uint32_t>(height) &&
+		static_cast<uint32_t>(pos.z) <= (twoLevel ? 1 : 0);
 }
 
 TerrainTile & CMap::getTile(const int3 & tile)