I was looking into strings v bytes into a bit more detail and started comparing the gas consumption between them. The following code was used:

pragma solidity ^0.5.0;
contract StringVersusByte {
string constant _string = "hello";
bytes32 constant _bytes = "hello";
function getAsString() pure public returns(string memory) {
return _string;
}
function getAsBytes() pure public returns(bytes32) {
return _bytes;
}
}

After deploying, I executed the the getAsBytes() first and saw that the execution cost was 196 gas.

I then looked to confirm this by stepping through the debugger and summing up the cost of all the op codes.

What I discovered was that it summed up to 172 and not 196 gas. I was out by 24 gas.

I then looked at the debugger and looked at the remaining gas field. It should reduce by the amount of gas but in step 3 it doesn’t. It reduces by 12 instead of 3 as can be seen in the video.

The culprit opcode is MSTORE and there are 2 MSTORE which makes up the missing 24 gas.

In the video, the remaining gas decreases by the expected amount until it reaches step 3.

This issue is highlighted as a bug in remix via: https://github.com/ethereum/remix-ide/issues/966 with the reason being: The cost of MSTORE is 3 gas, but the general cost if(sic) the step can be higher if the memory needs to be extended.

I don’t know what this means and still figuring it out (https://github.com/ethereum/remix-ide/issues/966)

I doubt that this is the reason but it is interesting to understand that the first 32 bytes are reserved to hold the length of the array.

Leave a Reply

Your email address will not be published. Required fields are marked *