1

I can not understand the difference in gas for the following problem. I generated a sha256 hash value and the output i chose to be lowercase hexadecimal. So the output value is hexadecimal string of 64 characters.Then i saved this value to a bytes32 variable inside a smart contract. The smart contract's code is:

pragma solidity ^0.4.23;

contract Project {
    bytes32 public value;

    function addValue(bytes32 val) public {
        value = val;
    }
}

Using remix, I noticed that the operation to add a value cost 43629 for some values and other 43693. So the difference is 64 gas. Can anyone help me understand why this is happening? I tested many values and the difference was 64 gas, was it random? I also tested to store it as string. Then the cost was constant for all inputs, maybe because the values have the same length as i said the inputs values have 64 characters.

  • Just a guess, but is the difference how many bytes are 0 in the input? – smarx Jun 5 '18 at 15:42
  • @smarx I tested it for two inputs that both have seven zeros. The one costed 43629 and the other 64 gas more so 43693 so i don't think the zeros matter. But nice i idea i haven't thought to check it before you notice it. – kathi Jun 5 '18 at 15:59
  • To clarify, you're counting the number of complete bytes that are 0s, not just the total number of 0s that occur in the hexadecimal string? (E.g. 0x102030 has no zero bytes, but 0x100020 has one zero byte.) – smarx Jun 5 '18 at 16:02
  • @smarx ok so i did it wrong i counted the number of zeros, silly me.. So you mean i should convert it to binary and then i should make teams of consecutive 8 bits and see if a "team" has all bits 0? sorry if my english are not good – kathi Jun 5 '18 at 17:24
  • Well, hexadecimal is fine. Every two hexadecimal characters is a single byte. If you would just share the values you're testing here, this would be much easier. – smarx Jun 5 '18 at 17:25
0

From the yellow paper:

Gtxdatazero 4 Paid for every zero byte of data or code for a transaction.

Gtxdatanonzero 68 Paid for every non-zero byte of data or code for a transaction

So if you replace a non-zero with a zero in your transaction data, you'll reduce the cost by 64 (68-4).

Note that consecutive 0s don't necessarily matter, just if they represent a full byte. It's easier to see if you separate bytes: d5 bf 2c b4 91 dd 63 f8 00 37 3f 16 ab 0f c4 86 ff e0 40 92 35 87 c0 0a dc ea d3 dc 4a 45 44 b6. So the second value you mentioned in your comment has exactly one zero byte.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.