0

Let's say we have the following payable method defined in a contract:

function foo() public payable {
  if (msg.value >= thresholdValue0) {
    // some logic..
  } else if (msg.value < thresholdValue0 && msg.value >= thresholdValue1) {
    // some logic..
  } else if (msg.value < thresholdValue1) {
    // some logic..
  }
}

Notice how msg.value is being used more than once (3 times, to be precise). I'm not sure if that would cost 3 times as much as the cost of a single msg.value read, and whether it would be more efficient to load it into memory first as follows:

function foo() public payable {
  uint256 msgValue = msg.value;
  if (msgValue >= thresholdValue0) {
    // some logic..
  } else if (msgValue < thresholdValue0 && msgValue >= thresholdValue1) {
    // some logic..
  } else if (msgValue < thresholdValue1) {
    // some logic..
  }
}

1 Answer 1

1

Second approach causes more gas, because of introducing uint256 msgValue because it occupies space. I verified both through remix, first approach uses 21195 gas while second one causes 21208 gas. All due to uint256 msgValue

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.