Solidity Gas Optimization tips with assembly you haven’t heard yet!

Bloqarl
5 min readApr 23, 2023
Photo by Lenny Kuhne on Unsplash

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

--

--

Bloqarl
Bloqarl

Written by Bloqarl

| Enhance Web3 Security | Build On-Chain | Master DeFi | If you share my same goals, I share everything I learn. My Twitter https://twitter.com/TheBlockChainer

Responses (1)