3
pragma solidity ^0.4.0;

contract SomeContract{

   address public owner;

    modifier ownerOnly{
        if(msg.sender == owner) _;  //would this use less gas than the modifier below?
    }

    modifier ownerOnly{
        if(msg.sender != owner) revert();  //is this modifier more secure?
        _;
    }

   function SomeContract(){
      owner = msg.sender;
   }
}
3

I created a simple contract and tested it in browser-solidity:

pragma solidity ^0.4.13;

contract TestContract {

    address owner;

    modifier ownerOnly1 {
        if(msg.sender == owner) _;  //would this use less gas than the modifier below?
    }

    modifier ownerOnly2 {
        if(msg.sender != owner) revert();  //is this modifier more secure?
        _;
    }

    function TestContract() {
        owner = msg.sender;
    }

    function foo()
    ownerOnly1    // or ownerOnly2
    returns (uint answer)
    {
        return 42;
    }
}

Here are the costs for calling foo() as owner:

For ownerOnly1: transaction cost 21570, execution cost 298.

For ownerOnly2: transaction cost 21573, execution cost 301.

However, when calling foo() from another account, ownerOnly2 causes an exception, but ownerOnly1 does not (returns 0 instead of 42). I suppose the ownerOnly2 effect is desirable.

Note that you can write this condition in a more readable way: require(msg.sender == owner) (see documentation on error handling).

1
  • @ZenosPavlakou you're welcome! You can accept it if it solved your problem :) Jul 31 '17 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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