In Solidity smart contracts, gas optimization requires minimizing direct read/write operations to blockchain storage by caching state variables into local memory variables before processing, and using unchecked arithmetic operations when overflow is impossible, as these optimizations can significantly reduce transaction costs by avoiding expensive EVM operations for each loop iteration.
Solidity Gas Optimization: EVM Storage and Unchecked Arithmetic
Added:sometimes you found a piece of your code that might use a little bit of optimization and then you optimize and you like what you see but you optimize a bit more and you like what you see and you optimize a bit more and you start to like it until is crazy how much gas you are saving but for these you have to know a little bit in detail how the evm works under the hood and it can get a little bit tricky so in this video we're going to cover a little bit why these gas savings are happening follow me to it for this we're going to use this contract and as you can see here we have something very simple we have a couple of state variables these variables are stored in the blockchain then in the constructor we are just populating one of these variables the array with a set of numbers and i want you to check these three functions over here these three functions actually are doing exactly the same they are taking the value of the addition of all the elements of this array and are populating our other state variable with that addition now i want you to look at these functions and try to figure out which one is going to be spending the less amount of gas and why so you think about it look at the functions and try to figure out which one is spending the less gas this is one exercise that was posted by patrick from channeling and i think it's very interesting because it actually teach you how to optimize for gas in a way that matters so a lot of the optimizations that you see in the internet or especially in twitter they are focusing on things that the optimizer in the compilers will take care sooner or later but this example is actually focusing on something that is a best practice that we should kind of know to implement manually as you might have already figured out the one that is spending the less amount of gas is the function c over here and the one that is the most expensive is function a and they are doing exactly the same now why is that happening and the reason is that in function a we are reading and writing directly to the blockchain in each iteration of this loop op cuts that means the machine language that is taking actions in the ethereum blockchain or evm compatible blockchain for reading and writing to the blockchain are actually quite expensive so this one is going to be quite expensive because of that in this other version though we are optimizing a bit and what we are doing is just caching our variable here at the total fonts which is one of our state variables to a memory variable here and we are having that variable being the one that is used during the execution of our loop this is saving us a lot of gas because we are not writing to the blockchain in the loop but the problem with this one is that we are not right into the blockchain but we are reading from the blockchain in each loop so that's not good enough so we go to option c which is actually the one that spends the less amount of gas and it is because we are caching both we are caching our total fonts and we are caching our memory array here for the array that we have on chain so we read from the blockchain only once we execute all our function with the copy of the array that we have in memory without having to read from the blockchain and then we just populate our variable as we were doing here so here we are optimizing only in writing here we are optimizing and reading and writing that will save us a lot of gas but is there anything else that we can do and actually we can this is a little bit kind of one of those esoteric optimizations but i think it's a nice trick for you guys to have under your belt and is related to the safe math library that used to be very popular back in the day back in the day when we have the same math library we have it for a reason and it was because solidity didn't revert on variable overflow each variable in solidity that is defined as a uiint or an integer has certain amount of values that it can hold and if you try to store more or a figure greater than that a specific number then in the current version of solidity it will just give you an error but back in the day that didn't exist it will just give you a value that was not correct so people develop safe math to manage those kind of arithmetic overflows then when new versions of solidity appeared starting from the version 0.8 this changed solidity was able to revert on overflows so there was no need for this safe math library but that made the arithmetic a little bit more expensive in terms of gas so if you can see where i'm going is here in this addition of this increasing of the variable i we are using the protected arithmetic of solidity which is called checked arithmetic and it will be cheaper gas-wise to just do unchecked arithmetic like the arithmetic of solidity was before day changes that introduced the reverting on overflows and we can do that very confidently because it will be very difficult for this variable i to overflow it's uh i do int 256 which is a very big number and no array is going to be as long as that so we could just do it unchecked and that's what we're going to do so we're going to introduce this function here which is going to be a helper for using the unchecked arithmetic and then instead of having this way of executing the function c or option c we are going to execute option d and instead of doing this type of thing we are going to put that i is equal to unsafe increase of i so when we do this we are actually increasing the value of i but with unchecked arithmetic just because we are introducing this one here and that will make it a lot cheaper to execute now let's get to test it for these tutorials i will just do everything in remix but remix has a kind of problematic javascript virtual machine for the evm work that is not that reliable for gas operations so we are going to inject web3 and that will connect my metamask here and that's what i will use to test so right now i will deploy this contract and we're going to wait a bit for this to appear so we have it already now we are going to execute the functions that we have here and we are going to go one by one and comparing what is the gas fee so we check this one that was option a and we can check that it's this amount of gas and if we check the gas price that is charging us which is 10 k we can see what is the actual gas of running this function so this is the value 97 400 we're going to reject that one now let's go to our option b which is kind of executing the same operation but we are doing some optimization there not the most that we could optimize and we can check it out right now and we went from 90 something to 76 something so that's a little bit better but still we can do better so we're going to reject that and we are going to go to option c which is the one that actually has the most optimizations so let's go here and we can see that it went from the 70 something amount of gas to only 57 000 so getting much better but if we go to the last one where we apply j unsafe math or they unchecked math to perform our addition here we can see that we shape a little bit of gas we shave around 1 000 gas due to that elimination of the check mat so guys here is what you can take from this very small video and very small tutorial try to avoid working directly with store values on the blockchain and i will recommend that you have certain convention for your storage variables that are in the blockchain in order anytime that you are using them you are doing it consciously and you have evaluated other options to implement your logic as you can see here i don't have any prefix in these storage variables in the local variables that i have in each function i do have this prefix and i use that to recognize when i'm working with local variables that are not stored in the blockchain the other part that you can take from this is that juicing unchecked arithmetic is actually cheaper but you have to know when you want to use it and it is only when you are sure that there wouldn't be errors in that arithmetic regarding overflow and other aspects like that because if not very bad results will happen in your calculations so only when it's safe you can use uncheck arithmetic and that will shape some gas from your operations now the other part that i want to touch upon before we leave is that there are a lot of small optimizations that you can do for example instead of i plus plus you could do here plus plus i that's actually part of the optimizations that the compilers will do for you in the future most likely so don't be greedy do all these kind of like optimization golfing only because it is an interesting way to get to know the evm and what you are doing in detail but don't obsess over it thank you very much guys this is daniel and see you in our next video
Up Next

Yul Assembly in Solidity: EVM Smart Contract Programming
@Reanblock
2.7K views•2023-03-05

Torrent File Format & Bencoding: A Technical Deep Dive
@AsliEngineering
12.5K views•2022-08-08

ERC-1155 Token Standard: Fungible and Non-Fungible Assets Explained
@MoralisWeb3
44.3K views•2021-06-09

Understanding Ethereum: A Comprehensive Beginner's Overview
@99Bitcoins
3.1M views•2018-06-26
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Blockchain & Crypto





































