Assignment Storage Design.
- When executing addEntity I found that the Array based test code took on average 1.3 times more execution gas than the Mapping version. Also on the first iteration of the Array code took 2x more gas.
Average execution gas for Array 28120 ( first iteration 43120)
Average execution gas for Mapping 22191 ( consistent over 5 iterations.)
I suggest that the overheads on Array gas costs are due to the use of a interim memory array and over head of indexing the array before storing in persistent storage.
- After the 5th iteration storing the data, updateEntity, caused a marginal increase in gas costs for the Array code.
Array gas cost 21714.
Mapping gas cost 20739.
As above suggest that the increase due to indexing array overhead. I repeated this test several times with the same results.
Obviously Mapping uses less gas from my test results and Array based uses more instructions which costs extra gas,
Any comments?
Thanks Mike
pragma solidity 0.8.0;
// Basic code for testing gas costs only .
contract gasMappingCost {
struct EntityStruct {
uint data;
address _address;
}
mapping (address => EntityStruct) public entityStructs;
function addEntity() public returns(bool success) {
entityStructs[msg.sender].data = 0; // initialise data
entityStructs[msg.sender]._address = msg.sender;
return true;
}
// msg.sender must match address 5 for test purposes when setting data.
function updateEntity(uint _data) public returns(bool success) {
entityStructs[msg.sender].data = _data;
return true;
}
}
/////////////////////////////////////////////////////////////////////////
pragma solidity 0.8.0;
// Basic code for testing gas costs only .
contract gasArrayCost{
struct EntityStruct {
uint data;
address _address;
}
EntityStruct[] public entityStructs;
function addEntity() public returns( bool success) {
EntityStruct memory newEntity;
newEntity._address = msg.sender;
newEntity.data = 0; // initialise data
entityStructs.push(newEntity);
return true;
}
// Assume manual matching of array index to match address 5 [4] for test purposes when setting data
function updateEntity(uint arrayIndex, uint _data) public returns(bool success) {
entityStructs[arrayIndex].data=_data;
return true;
}
}
ype or paste code here