Created
April 20, 2022 13:44
-
-
Save ryestew/82c845ede8135e484aa9d626d632faf1 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.7+commit.e28d00a7.js&optimize=true&runs=200&gist=
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.10; | |
// gas golf | |
contract MusketeerGas { | |
// The munitions manager of the Musketeer corps of Bannon Cocq has a limited amount of gunpowder (GAS) for their murder | |
// They need to use what that have wisely. | |
// In preparing the murder of X, they plan how much gunpowder to use. Their stock is limited and their | |
// boss Bannon Cocq will be upset with them if they use too much. | |
// how much is used in this contract as is? | |
// | |
// start - 50908 gas | |
// use calldata - 49163 gas | |
// load state variables to memory - 48952 gas | |
// short circuit - 48634 gas | |
// loop increments - 48244 gas | |
// cache array length - 48209 gas | |
// load array elements to memory - 48047 gas | |
uint public total; | |
// start - not gas optimized | |
// function sumIfEvenAndLessThan99(uint[] memory nums) external { | |
// for (uint i = 0; i < nums.length; i += 1) { | |
// bool isEven = nums[i] % 2 == 0; | |
// bool isLessThan99 = nums[i] < 99; | |
// if (isEven && isLessThan99) { | |
// total += nums[i]; | |
// } | |
// } | |
// } | |
// gas optimized | |
// [1, 2, 3, 4, 5, 100] | |
function sumIfEvenAndLessThan99(uint[] calldata nums) external { | |
uint _total = total; | |
uint len = nums.length; | |
for (uint i = 0; i < len; ++i) { | |
uint num = nums[i]; | |
if (num % 2 == 0 && num < 99) { | |
_total += num; | |
} | |
} | |
total = _total; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment