请看测试结论:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "hardhat/console.sol";
contract modifierTest {
address public owner;
modifier onlyOwner() {
//require(owner == msg.sender, "Ownable: caller is not the owner");
_checkOwner();
_;
}
// Gas cost: deploy--85863 add funtion--execution:901790
function add() public onlyOwner {
}
function addone() public onlyOwner {
}
function addtwo() public onlyOwner {
}
function _checkOwner() internal view virtual {
// console.log("Owner :", owner);
// console.log("Owner exec by:", msg.sender);
require(owner == msg.sender, "Ownable: caller is not the owner");
}
}
//直接在修饰器中执行逻辑
//add-require
//transaction cost:23635 execution cost:2571
//把具体逻辑放在方法中,然后再修饰器中执行
//add-_checkOwner
//transaction cost:23650 execution cost:2586
感兴趣的话,可以自己对比下add-require和add-_checkOwner的字节码,就知道什么原因是这样了
// 以下是修饰多个方法的场景消耗gas的结果
//2 add--修改两个方法
//require
//transaction cost:203979 execution cost:140181
//_checkOwner
//transaction cost:177673 execution cost:115563
//3 add--修饰三个方法
//require
//transaction cost:239072 execution cost:173012
//_checkOwner
//transaction cost:184299 execution cost:121763