diff --git a/contracts/utils/math/Math.sol b/contracts/utils/math/Math.sol index d7fd2f64d15..2c8dd20d440 100644 --- a/contracts/utils/math/Math.sol +++ b/contracts/utils/math/Math.sol @@ -474,8 +474,26 @@ library Math { * @dev Returns whether the provided byte array is zero. */ function _zeroBytes(bytes memory byteArray) private pure returns (bool) { - for (uint256 i = 0; i < byteArray.length; ++i) { - if (byteArray[i] != 0) { + // Fast path: scan 32-byte words first to reduce gas on large inputs. + uint256 len = byteArray.length; + uint256 offset = 0; + + while (len >= 32) { + bytes32 word; + assembly ("memory-safe") { + // Load a full 32-byte word starting at current offset + word := mload(add(add(byteArray, 0x20), offset)) + } + if (word != 0) { + return false; + } + offset += 32; + len -= 32; + } + + // Tail check (< 32 bytes) + for (uint256 i = 0; i < len; ++i) { + if (byteArray[offset + i] != 0) { return false; } }