2 contracts as per below
1. arrayStorage contract:
pragma solidity 0.8.0;
contract arrayStorage {
struct Entity{
uint data;
address _address;
}
Entity [] public entityArray;
function addEntity(uint _data) public returns (bool entityAdded) {
Entity memory newEntity;
newEntity._address = msg.sender;
newEntity.data = _data;
entityArray.push(newEntity);
return true;
}
// assuming the index of the address to be updated is known
function updateEntity(uint index, uint _data) public returns (bool success) {
require(entityArray[index]._address == msg.sender, "only address owner can update data");
entityArray[index].data = _data;
return true;
}
}
2. mappedStorage contract:
pragma solidity 0.8.0;
contract MappedStorage {
struct Entity{
uint entityData;
address entityAddress;
}
mapping (address => Entity) public mappedEntities;
function addEntity(uint entityData) public returns (bool entityAdded) {
Entity memory newEntity;
newEntity.entityData = entityData;
newEntity.entityAddress = msg.sender;
mappedEntities[msg.sender] = newEntity;
return true;
}
function updateEntity(uint newData) public returns (bool entityUpdated) {
mappedEntities[msg.sender].entityData = newData;
return true;
}
}
Gas cost summary:
1. Adding an entity:
Array: 1st addition: 88489, following 4 additions 71389 each, total 374045 gas
Mapping: all 5 additions cost 66375 of gas, total 331765
Conclusion: Mapping is cheaper: for the first addition mapping spends aprox. 25% less, the total gast cost of adding 5 entities differs in favour of mapping of aprox. 11,3%. The larger difference regarding the first addition is due to the fact that array addition gas cost drop as of the second addition while the gas cost for mapping additions remains the same.
2. Updating the 5th entity:
Array: 31725
Mapping: 26943
Conclusion: updating an entity of a mapping is aprox 15% cheaper than updating an array entity.
Why is mapping cheaper than array:
“An Array in Solidity is basically a struct with this structure”
struct Array{
mapping(uint => someType) items;
uint length;
}
(source: (https://ethereum.stackexchange.com/questions/37549/array-or-mapping-which-costs-more-gas).
It appears that adding this additional struct code and mapping for processing an array in solidity adds additional load to the execution of the code, hence the higher cost of arrays.
Doubt:
Comparing my code to my fellow colleagues in the forum I’ve noted that their updating gas cost is much cheaper than mine but I couldn’t figure out why that is. I’d therefore greatly appreciate any hints from your end to figure this out.
Thanks for your help!
Yestome.