A Few Simple Tricks to Reduce the Gas Consumption in Solidity

pragma solidity ^0.8.4;

contract Playground {
address payable owner = payable(msg.sender);

function withdraw() public {
if (msg.sender != owner)
revert(" This is a sample error string! You should not use it because it's costly!");

owner.transfer(address(this).balance);
}

}
pragma solidity ^0.8.4;

error Unauthorized (address caller); // here is our custom error
contract Playground {
address payable owner = payable(msg.sender);


function withdraw() public {
if (msg.sender != owner)
revert Unauthorized(msg.sender);

owner.transfer(address(this).balance);
}
// ...
}
pragma solidity ^0.8.4;

contract Test{

unint public n=5;

function nonoptimized() external view returns (unint) {

uint a=0;
for(uinit i=0; i<n; i++){ // in each iteration, we have to check the local state variable n, which is a slow approach
a+=1;
}
return a;
}

function optimized() external view returns (unint) {

uint a=0;
unit cach_n = n; // here we cach the local state variable into a local variable that does not consume expensive memory
for(uinit i=0; i<cach_n; i++){ // in each iteration, we have to check the local state variable n, which is a slow approach
a+=1;
}
return a;
}

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mo Ashouri

Mo Ashouri

22 Followers

Mo has a Ph.D. in Cyber Security and is the founder of ByteScan.net, a blockchain audit firm. Mo specializes in Solidity, Rust, and Golang.