pragma solidity ^0.5.0; // 'compare' and 'equal' functions come from github.com/ethereum/dapp-bin/library/stringUtils.sol; contract OptimizingStringCompare { function compareStringsWithLib() public pure returns (bool) { return equal("totally different1", "totally different2"); } function compareStringsWithHash() public pure returns (bool) { return areStringsEqual("totally different1", "totally different2"); } function areStringsEqual(string memory lhs, string memory rhs) private pure returns (bool) { return keccak256(bytes(lhs)) == keccak256(bytes(rhs)); } /// @dev Compares two strings and returns true if they are equal. function equal(string memory _a, string memory _b) private pure returns (bool) { return compare(_a, _b) == 0; } function compare(string memory _a, string memory _b) private pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } }
0.4.18