My contracts
Array
pragma solidity 0.7.5;
pragma abicoder v2;
contract Arraycost {
address private owner;
uint x;
constructor() {
owner = msg.sender;
}
struct Entity{
uint data;
address _address;
}
Entity[] private entity;
function addEntity() public {
x += 1;
Entity memory newEntity;
newEntity.data = x+1;
newEntity._address = msg.sender;
entity.push(newEntity);
}
function updateEntity(uint _number, uint _newData) public {
entity[_number].data = _newData;
}
function viewEntity(uint _number) public view returns (Entity memory){
return entity[_number];
}
}
Mapping
pragma solidity 0.7.5;
pragma abicoder v2;
contract Mapcost {
address private owner;
uint x;
constructor() {
owner = msg.sender;
}
struct Entity{
uint data;
address _address;
}
mapping(uint => Entity) entity;
function addEntity() public {
x += 1;
entity[x].data += x+1;
entity[x]._address = msg.sender;
}
function updateEntity(uint _number, uint _newData) public {
entity[_number].data = _newData;
}
function viewEntity(uint _number) public view returns (Entity memory){
return entity[_number];
}
}
When executing the addEntity function, which design consumes the most gas (execution cost)? Is it a significant difference? Why/why not?
Mapping consume fewer execution cost. In my case I have more lines of code for this function in the array contract and I suppose (i’m not sure) when i push a new data into the array we need some kind of extra code. (more code to execute more expensive)
Array
First Addentity
The others Addentity
Mapping
First Addentity
The others Addentity
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 consume more, if you have more data more consume because the program need to look every data until find the result
Array
Mapping