[Ethereum] Array or mapping, which costs more gas

arrayscontract-designmapping

I have been using arrays of struct for my contract. In Remix IDE with the private network, one function costs me around 300,000 gas. However, if I call the same function from web3js, it costs me a lot and sometimes the cost exceeds block gas limit which was set to 9,999,999.

Could you please let me know if array costs more gas than mapping does?

Best Answer

Array does cost more than mapping, but that's because it's not doing the same thing. An Array in Solidity is basically a struct with this structure

struct Array{
  mapping(uint => someType) items;
  uint length;
}

On top of this, Arrays have bounds checking around length such that attempts to access an item in the items mapping with a 0>index>length-1 will assert. You can roll-your-own "Array" like struct like above if you don't need functionality for bounds checking

Edit: To clarify, the likening of an array to a mapping+length variable was just an example. An array does store the actual elements in order in storage starting from the slot that is the hash of the location in storage of the array's length. A mapping on the other hand stores like you would expect, as a hash of the location in storage of the root of the map (r) and the individual key (k), i.e. the location of value v with key k is keccak256(r+k)

Related Topic