Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize 《5、operator.md》 #15

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/source/05.operator.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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++;
}
}
}
}
```

### 赋值运算符

- `= `(简单赋值)
Expand Down