We have a struct:
struct structEx {
uint num;
}
And an array:
structEx[] arr;
Have a look at this code snippet, which just instantiates the struct and push:
function f() public {
structEx s = structEx(0);
arr.push(s);
}
The above method creates new storage from struct reference and when we push it to arr, copy it to array's storage.
Another way to do this:
function f() public {
structEx memory s = structEx(0);
arr.push(s);
}
The above method stores struct instance in memory and copies to storage when pushed to array.
So, as per my understanding second should cost lesser gas than first. Is this correct? feel free to add your thoughts and experience!
f1is saving the value of the struct in a local variable and then it push this value in the storage.f2will write nothing in memory (explicitly) and just push the struct in the storage. Probably is an optimization of the EVM that will prevent to waste memory space needed forf1(even if actually you need to create the object in both case and so the memory will be used somehow). But its just an empirical deduction since I don't know how it works the EVM and the gas calculation at low level. – qbsp Apr 12 '18 at 08:13