在区块链的时间中代码即法律,交易即金钱。每一次智能合约的运行,都会根据复杂度的不同消耗Gas费。开发人员在编写智能合约时,不仅要考虑安全因素,还要考虑代码的优化,以便用户在调用智能合约的过程中节约可观的Gas费用。常见的节约gas的方法有如下几种方式:

  • calldata 替换 memory
  • 将状态变量加载到内存memory
  • 用 ++i 替换 for 循环 i++
  • 缓存数组元素
  • 短路
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

// gas golf
contract GasGolf {
// 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
// uncheck i overflow/underflow - 47309 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; ) {
uint num = nums[i];
if (num % 2 == 0 && num < 99) {
_total += num;
}
unchecked {
++i;
}
}

total = _total;
}
}