Solidity Gas Optimization tips with assembly you haven’t heard yet!
If you can’t read this article because of the firewall, go here to read it for free!
When it comes to writing efficient and cost-effective smart contracts on the Ethereum blockchain, every little bit of gas savings counts. One way to optimize gas usage is by using assembly code instead of Solidity in certain parts of your contract.
In this article, we will explore how using assembly code can help you save gas in various scenarios, from hashing and math operations to writing to storage and checking for zero addresses. We will provide examples of Solidity code and their corresponding assembly implementations, along with gas usage comparisons so you can see for yourself the potential gas savings.
1. Use assembly to hash instead of solidity
function solidityHash(uint256 a, uint256 b) public view {
//unoptimized
keccak256(abi.encodePacked(a, b));
}
Gas: 313
function assemblyHash(uint256 a, uint256 b) public view {
//optimized
assembly {
mstore(0x00, a)
mstore(0x20, b)
let hashedVal := keccak256(0x00, 0x40)
}
}
Gas: 231