Reputation: 365
Coming from a node background and wondering what is best practice for Soldidty development regarding variables for cleaner code.
I'm aware that any variable costs gas and thus we should be very judicious in what variables we declare. I'm wondering if the gas cost for saving a variable to make code easier to read is frowned upon or if the gas is negligble in the long run. Example below with a struct and then a function:
struct Balance {
uint totalBalance;
uint numPayments;
}
mapping(address => Balance) public deposits;
function sendMoney() public payable {
// this is just ready to accept money;
Balance storage userAccount = deposits[msg.sender]; <--- is this bad practice or negligible?
// do a bunch of daisy chained operations...
}
Are gas costs for these things negligible or should we just stick to keying into variables all daisy chained together?
Thanks!
Upvotes: 0
Views: 61
Reputation: 43531
All reference type variables (including struct
) within a function need to have a data location specified. There's no default value, so the compiler throws an error if you don't specify it.
Declaring the pointer to the storage variable and using it for one write operation is approx. 100 gas more expensive compared to performing the write directly to the storage variable. In a simple test (compiled without the optimizer option), I measured 65,562 gas writing to the deposits
mapping directly, compared to 65,664 (approx. 100 more) gas using the userAccount
storage pointer.
A usual transaction cost tens of thousands of gas, which makes the potential savings on multiple writes around one percent. But it really depends on your use case whether you want/need to optimize to this extent of savings and make the code less readable - or not.
Upvotes: 2
Reputation: 858
As far as I know the cost can be negligible if the variable is a memory variable if you write to storage it will be expensive, so try to do that kind of calculations in memory variables and write to storage only when needed
Upvotes: 0