[Ethereum] Dynamic arrays VS mappings when it comes to gas usage

arraysfeesgasmappingsolidity

I'm puzzled what is more efficient to use, from the point of gas consumption (storage and execution), dynamic array or the mapping and element counter.

To be more clear, I'm not asking the basic data structure usage paradigms that we all should know, nor about pros and cons that each have, rather I want to know what is more gas efficient.

Let me give you an example in a sort of pseudo code:

contract DataStorage {

    //mapping and data counter
    mapping (uint256 => uint256) sequentialData1;
    uint256 sequentialData1Counter;

    //dynamic array
    uint256[] sequentialData2;

    function addDataToMapping(uint256 _newData) {
        sequentialData1[sequentialData1Counter++] = _newData;
    }

    function addDataToDynamicArray(uint256 _newData) {
        sequintialData2.push(_newData);
    }
}

Don't think about deleting elements and so on, let's say I just want to add new data to array and be able to access them by index.

Best Answer

There's some difference in behavior but in your example the gas consumption is about the same. An array has to maintain its length and your mapping uses a counter instead. All data in the array is stored continuously and the mapping is spread in the store but that doesn't affect the costs.

Related Topic