Here are my results.
First, the code:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract simpleMapping {
struct Entity{
uint data;
address _address;
}
mapping (address => Entity) public entities;
function addEntity(uint _data) public returns(bool success) {
Entity memory newEntity;
newEntity.data = _data;
newEntity._address = msg.sender;
entities[msg.sender] = newEntity;
return true;
}
function updateEntity(address _updater, uint _data) public returns(bool success) {
entities[_updater].data = _data;
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract simpleArray {
struct Entity{
uint data;
address _address;
}
Entity[] public entities;
function addEntity(uint entityData, address entityAddress) public returns(bool success) {
Entity memory newEntity;
newEntity.data = entityData;
newEntity._address = entityAddress;
entities.push(newEntity);
return true;
}
function updateEntity(uint _index, uint _data) public returns(bool success) {
entities[_index].data = _data;
return true;
}
}
1/ When executing the addEntity function, which design consumes the most gas (execution cost)?
Simple mapping
gas : 76357
transaction cost : 66397
execution cost : 66397
Simple array
gas : 102493
transaction cost : 89124
execution cost : 89124
Is it a significant difference? 34 % more with array method
Why? With the array, there is an index to set up, not with the mapping ?
2/ Add 5 Entities into storage using the addEntity function and 5 different addresses. Then update the data of the fifth address you used. Do this for both contracts and take note of the gas consumption (execution cost). Which solution consumes more gas and why?
Simple mapping - 2 first transaction
gas : 76357
transaction cost : 66397
execution cost : 66397
Simple mapping
gas : 76371
transaction cost : 66409
execution cost : 66409
Simple array – first transaction
gas : 102493
transaction cost : 89124
execution cost : 89124
Simple array – 2nd transaction
gas : 82828
transaction cost : 72024
execution cost : 72024
Simple array – next ones
gas : 82842
transaction cost : 72036
execution cost : 72036
The array always consumes more gas but the gap is smaller after the first transactions.
I guess this is again due to the indexing of the array.