美文网首页gas优化
gas优化: 状态变量的可视范围(public, private

gas优化: 状态变量的可视范围(public, private

作者: 梁帆 | 来源:发表于2022-11-06 14:19 被阅读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, privateinternal
    我们可以从部署和执行两个方面探求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

    相关文章

      网友评论

        本文标题:gas优化: 状态变量的可视范围(public, private

        本文链接:https://www.haomeiwen.com/subject/sdxutdtx.html