Solidity Gas Costs: Initial vs Subsequent Storage in Mapping

evmgassoliditytransactions

I have the following simple storage code:

pragma solidity ^0.4.17;

//The Oracle contract provides the reference prices for the contracts.  Currently the Oracle is updated by an off chain calculation by DDA.  Methodology can be found at www.github.com/DecentralizedDerivatives/Oracles
contract Test_Oracle {

  /*Variables*/
  //Mapping of documents stored in the oracle
  mapping(uint => uint) oracle_values;

  //Allows the owner of the Oracle to store a document in the oracle_values mapping. Documents
  //represent underlying values at a specified date (key).
  function StoreDocument(uint _key, uint _value) public {
    oracle_values[_key] = _value;
  }

  //Allows for the viewing of oracle data
  function RetrieveData(uint _date) public constant returns (uint data) {
    return oracle_values[_date];
  }
}

Now I create the Test Oracle and do the following transactions:

a)StoreDocument(1,1000)
b)SotreDocument(1,1000)
c)StoreDocument(1,1000)
d)StoreDocument(2,999999999999)

The following transaction and execution costs are recorded:

a)42024,20304
b)27024,5034
c)27024,5034
d)42216,20304

Some questions…
Why are a and b different?
Why are a and d different on transaction cost but not execution cost?

Maybe someone a bit more familiar with the low level EVM knows an answer. Thanks for any help in advance!

Best Answer

https://github.com/djrtwo/evm-opcode-gas-costs/blob/master/opcode-gas-costs_EIP-150_revision-1e18248_2017-04-12.csv is helpful.

In short, SSTORE (storing a value) costs 20,000 gas if you're storing a non-zero value where there was previously a zero (as in your first example), and it costs 5,000 gas if you're storing a non-zero value where there was already a non-zero value.