Created
July 25, 2023 11:52
-
-
Save TehilaFavourite/af25421b33010ccaed385ea35f5ca362 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
// Bad approach: Unnecessary state updates | |
contract BadLocalVariables { | |
uint256 public total; | |
function addNumbers(uint256 a, uint256 b) public { | |
total = a + b; // Consumes gas for state update | |
} | |
} | |
// Good approach: Use local variables for intermediate calculations | |
contract GoodLocalVariables { | |
uint256 public total; | |
function addNumbers(uint256 a, uint256 b) public { | |
uint256 sum = a + b; // State not updated here, saving gas | |
total = sum; // State updated only once, after the calculations | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment