Why in solidity, i++
& ++i
works the same but one costs a little bit more gas?
Take a look at this contract:
contract foobar {
uint[] public arr = [1,2,3,4,5];
function find() public view returns(bool) {
for(uint i = 0; i < arr.length; i++ /*++i*/) {
if(arr[i] == 5) {
return true;
}
}
return false;
}
}
When I run this contract using i++
this is what the contract's cost is:
// i++
// gas 388824 gas
// transaction cost 338107 gas
// execution cost 338107 gas
// foobar.find() execution cost 36221 gas
And when I run the same function using ++i
, this is what the cost is:
// ++i
// gas 388327 gas
// transaction cost 337675 gas
// execution cost 337675 gas
// foobar.find() execution cost 36201 gas
Clearly, i++
costs more gas than ++i
, But Why?
Thanks
i++
not getting inlined. Try--via-ir
with the optimizer, they should have identical gas cost, except when the semantics are different.