gas优化: 状态变量的可视范围(public, private
2022-11-06 本文已影响0人
梁帆
有下属合约:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract A {
uint public value = 100;
uint private temp = 0;
function get() external returns (uint) {
temp = 1;
return value;
}
function set() external {
value = 99;
}
}
contract B {
uint private value = 100;
uint private temp = 0;
function get() external returns (uint) {
temp = 1;
return value;
}
function set() external {
value = 99;
}
}
contract C {
uint internal value = 100;
uint private temp = 0;
function get() external returns (uint) {
temp = 1;
return value;
}
function set() external {
value = 99;
}
}
三个合约只有value
变量的可视范围有区别,分别是public
, private
和internal
。
我们可以从部署和执行两个方面探求gas消耗量,最后的结果为:
合约 | 可视范围 | 执行 | gas消耗量 |
---|---|---|---|
A | public | 部署 | 134009 |
A | public | get | 45615 |
A | public | set | 26244 |
B | private | 部署 | 124921 |
B | private | get | 45593 |
B | private | set | 26222 |
C | internal | 部署 | 124909 |
C | internal | get | 45593 |
C | internal | set | 26222 |
可以得出结论:
部署的时候,gas消耗量排行为:public > private > internal
;
获取的时候,gas消耗量排行为:public > private = internal
;
设置的时候,gas消耗量排行为:public > private = internal
;