# gas 优化

By [clicknft](https://paragraph.com/@clicknft-2) · 2022-06-11

---

把之前看过的笔记一下

1.减少合约call调用。例如汇编下面会有每次的extencodesize调用

2.32字节放一块的常规做法。不过除了这个，在保存的时候，一个group（32字节一组的）的store要尽量连续同时操作（读和写，不要中间run其它代码打断）。记住除了空间，还有时间维度考虑

![](https://storage.googleapis.com/papyrus_images/1b417df7ad120cc016b16c08fe23b74f1f325ad726a00cf44824423e732aec90.png)

3.**循环里面减少storage变量的读和写，可以临时拿个memory变量来过渡，操作完保存回storage**

4.可以考虑用uncheck来规避0.8.4编译器后自动加入的溢出检测，在循环的里面记得使用，例如i++

5.input data，一个非0 byte需要68gas,0 byte需要4 gas

6.函数声明是external时一定程度可以省gas,因为会把函数参数保存在calldata

7.变量类型使用。为什么uint256比uint8使用更少gas,因为是按32字节操作，只取8位（1个字节）的话，需要在32字节里面再额外操作取1个字节

![](https://storage.googleapis.com/papyrus_images/bfbca43c7f70a277479785b2510d3956893af017661c7849787ad8f4353ad928.png)

PS：uintxx，xx/8就是多少个字节，uint256,就是256/8=32,32个字节

---

*Originally published on [clicknft](https://paragraph.com/@clicknft-2/gas)*
