syntax
supporting for
and while
loop,which syntax is similar to javascript language
core risk
looping may cause high-cost gas usage.
security warning
Never iterate over a dynamic storage array, since its length is unpredictable and can grow indefinitely.
Best practice
use mapping to instead of loop, because Mapping lookups always cost a fixed amount of gas.
❌ bad:as users grow, gas fee will grow indefinitely
address[] public users;
function isUser(address _user) public view returns (bool) {
for (uint i = 0; i < users.length; i++) {
if (users[i] == _user) {
return true;
}
}
return false;
}
✅ good
mapping(address => bool) public isUserMapping;
function isUserEfficient(address _user) public view returns (bool) {
return isUserMapping[_user];
}
Top comments (0)