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;
}
}
1 Answer
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).
-
@ZenosPavlakou you're welcome! You can accept it if it solved your problem :) Jul 31, 2017 at 16:54