3
contract test {
  address public _onwer;

  error NotOwner();

  modifier OnlyOwner1() {
      if(msg.sender != _onwer) {
          revert NotOwner();
      }
      _;
  }

  function OnlyOwner2() private view {
      if(msg.sender != _onwer) {
          revert NotOwner();
      } 
  }

  function toDoSomething1() public view OnlyOwner1() {
      // to do something
  }

  function toDoSomething2() public view {
      OnlyOwner2();
      // to do something
  }
}

Looking at the above code as an example toDoSomething1() and toDoSomething2(), which method is more efficient, modifier(OnlyOwner1()) or function(OnlyOwner2())?

I would really appreciate it if you could explain why.

2 Answers 2

2

I've tested in Remix, although both function calls reverted, both methods had approximately similar execution cost (Cost only applies when called by a contract), with toDoSomething1() 23410 gas vs. toDoSomething2() 23403 gas. They're both nearly as efficient as they perform the same check of condition prior to executing the function. But for best coding practice, I would declare the modifier using the modifier keyword as they can be inherited and overridden by derived contracts as needed.

2

It would depend on the code, but there wouldn't generally be much in it in terms of execution, but could be a significant different in the size of the deployed code. When the code is deployed the modifier code is inserted into or wrapped around each of the functions it is used with.

in your example

  function toDoSomething1() public view OnlyOwner1() {
      if(msg.sender != _onwer) {
          revert NotOwner();
      } 
      // to do something
  }

or

modifier testMod {
    ++stateVar1;
    _;
    ++stateVar2;
}

function testFunc() public testmod {
    --stateVar3;
}

becomes

function testFunc() public {
    ++stateVar1;
    --stateVar3;
    ++stateVar2;
}

if a modifier is used many times it can result in a lot of code duplication which can make deployment more expensive, or could make enough of a difference to push the contract size over the limit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.