3

If selfbalance() and address(this).balance are the same, except one costs less gas, what stops the Solidity compiler from optimizing it away?

I'm sure there is a reason, I'm interested in knowing what are those exact situations where this optimization would lead to an unexpected behavior.

1 Answer 1

1

Solidity 0.5.13 introduced in commit 61d6c12b7:

Use selfbalance for address(this).balance.

The optimization works all the time and there is no difference between the two. By definition see EIP-1844:

SELFBALANCE pushes the balance of the current address to the stack


More information

Solidity 0.5.14

Set the default EVM version to "Istanbul".

which activated (by default) the code added in 0.5.13

Code Generator: Use SELFBALANCE opcode for address(this).balance if using Istanbul EVM.

(hat tip to this question for helping identify the nuances: Solidity 0.6.0 address(this).balance throws error invalid opcode)

EIP-1844 explains SELFBALANCE gas cost

is priced at 5 (GasFastStep) instead of 2 (GasQuickStep), like other similar operations: the EVM execution engine still needs a lookup into the (cached) trie, and balance, unlike gasPrice or timeStamp, is not constant during the execution, so it has a bit more inherent overhead

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.