Skip to content

Instantly share code, notes, and snippets.

@ashwinYardi
Created July 19, 2022 06:58
Show Gist options
  • Save ashwinYardi/10694a0b98724e611a3a0d644dd45fa8 to your computer and use it in GitHub Desktop.
Save ashwinYardi/10694a0b98724e611a3a0d644dd45fa8 to your computer and use it in GitHub Desktop.
Solidity program to demonstrate how modifying storage items is expensive
// Solidity program to demonstrate
// how modifying storage items is expensive
pragma solidity ^ 0.8.5;
contract StorageVariableDemo
{
uint public temp;
/*
* @description:Below function runs the for loop 100 times and updates
* storage variable temp each time.
*/
function expensiveFunction() external {
for (uint i = 0; i < 100; i++){
temp++;
}
}
/*
* @description: Below function runs the for loop 100 times and
* memory variable 100 times. This memory variable is then assigned back to temp.
*/
function cheaperFunction() external {
uint j = temp;
for (uint i = 0; i < 100; i++){
j++;
}
temp = j;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment