From 6ccfa49cadd48b550c4a58932532ea96ebff6e50 Mon Sep 17 00:00:00 2001 From: jmz <1125378902@qq.com> Date: Fri, 2 Jun 2023 18:13:29 +0800 Subject: [PATCH] optimize 5 --- docs/source/05.operator.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/source/05.operator.md b/docs/source/05.operator.md index a9000e4..7d195de 100644 --- a/docs/source/05.operator.md +++ b/docs/source/05.operator.md @@ -130,6 +130,10 @@ function f(uint a, uint b) pure public returns (uint) { #### for 循环中,++i 更省钱 +通过汇编执行流程比较发现, i++比++i 多做了一次 `DUP(3 gas)`和`POP(2 gas)`操作, 10次循环正好是50gas, +多出来的 22 gas是 因为 test2 会比 test1 优先命中的原因. + + ``` // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; @@ -151,6 +155,25 @@ contract Test { } ``` +更省gas 的操作 +``` +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.17; + +contract Test { + // 25153 gas + function test1() public pure returns (uint256 temp) { + for (uint256 index = 0; index < 10; ) { + temp += index; + unchecked{ + // index++ 与++index 不会出现gas上的差异 + index++; + } + } + } +} +``` + ### 赋值运算符 - `= `(简单赋值)