I would like to validate with the community that my gas saving measure make sense and are actually saving gas when using loops in a smart contract.
After some research I found out that;
- setting the state to a first value cost more gas than updating a value that was already there.
- Dealing with Storage is the most expensive operation.
- Using loops is dangerous.
With this in mind I came up with this.
contract {
struct _DATA{
uint256 _id;
address _user;
string _attr;
}
function addStorage(some attrib){
// this is an expensive function to add a new entry to the struct
// we would add a ne entry and change the state for the first time for all attribute
}
function updateAttrib(some attrib){
// this function will update the storage saving gas because data was already written there.
// will cost less gas to update a few value. Would also help regulate the size of the _DATA
}
To perform multiple task on storage with loops and try to reduce gas.
function step1(uint256[] _id) public {
// require()
// first step verifications
// make sure we have an exit point to the loop before starting it
step2(_id)
}
function _step2isFirstLoop(_id) internal {
uint256 i;
for(i==0;i<_id.length;i++){
// The step 2 perform verification to process transactions
// Using memory to save on gas and evaluate the data
_DATA memory data = data[i];
require(thing to be true);
// should revert here in memory rather than in storage loop
}
// all verification passed
_step3(_id)
}
function _step3(_ip) internal {
//the last loop
for(...){
_DATA storage data = data[]
// this is where we actually update the storage data
}
}
Is there a way i could save even more gas?