Questions/Answers:
- When executing the addEntity function, which design consumes the most gas (execution cost)? Is it a significant difference? Why/why not?
Array = 68663 gas (46948 with uint8; 51563 for subsequent additions with uint256) VS Mapping = 23062 gas (23171 with uint8).
Array consumes the most gas, a significant difference; this is because in the EVM, arrays are stored as allocations instead of being stored sequentially in memory (i.e. arrays are ‘less efficient’, in terms of storage and management cost.)
- 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?
Array = 10653 gas (8784 with uint8) VS mapping = 5918 gas (6049 with uint8).
Array consumes the most gas; because of the array’s inherent inefficiency compared to the mapping.
Code:
pragma solidity 0.8.0;
contract onlyArrayStorage {
struct Entity {
address _address;
uint data;
}
Entity[] public entities;
function addEntity(address entityAddress, uint entityData) public returns(Entity memory) {
Entity memory newEntity;
newEntity._address = entityAddress;
newEntity.data = entityData;
entities.push(newEntity);
return entities[entities.length - 1];
}
function updateEntity(uint rowNumber, address entityAddress, uint entityData) public returns(bool success) {
entities[rowNumber]._address = entityAddress;
entities[rowNumber].data = entityData;
return true;
}
}
pragma solidity 0.8.0;
contract onlyMappingStorage {
struct Entity {
address _address;
uint data;
}
mapping(address => Entity) public entities;
function addEntity(address entityAddress, uint data) public returns(bool success) {
entities[entityAddress].data = data;
return true;
}
function updateEntity(address entityAddress, uint data) public returns(bool success) {
entities[entityAddress].data = data;
return true;
}
}