You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solidity动态函数执行与枚举实现的Gas效率对比咨询

Solidity中两种push实现的Gas效率对比

结论:用uint8模拟枚举的push实现Gas效率明显更高

原因很直接:

  • 动态函数执行的版本需要处理函数指针的调用逻辑,EVM在执行这类内部函数调用时,会产生额外的栈操作、上下文切换开销,光是CALL相关指令的Gas消耗就比简单的分支判断高很多。而且op函数的调用还需要传递参数、处理返回值,这些步骤都要占Gas。
  • 而uint8分支的版本是纯本地逻辑:只做一次简单的数值比较(operation == 1),然后直接执行加法或减法,都是EVM最基础的算术操作,分支跳转的开销极低,完全没有额外的函数调用成本。

贴出两种实现的代码:

动态函数执行的push实现

function push(
    History storage self,
    function(uint256, uint256) view returns (uint256) op,
    uint256 delta
) internal returns (uint256, uint256) {
    return push(self, op(latest(self), delta));
}

uint8模拟枚举的push实现

function push(
    History storage self,
    uint8 operation,
    uint256 delta
) internal returns (uint256, uint256) {
      if(operation == 1) {
          return push(self, latest(self) + delta);
     }
    return push(self, latest(self) - delta);
}

补充一点:如果你的操作逻辑更复杂,动态函数调用的灵活性会更高,但Gas成本的差距只会更大——每多一次函数调用,就多一次CALL相关的开销。而分支判断的方式,哪怕再加几个操作类型,也只是多几个简单的条件判断,Gas增长非常有限。

内容的提问来源于stack exchange,提问作者Ritzy Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:15:36