...by Daniel Szego
quote
"Simplicity is the ultimate sophistication."
Leonardo da Vinci

Monday, January 1, 2018

Solidity gas optimization - memory arrays


Whenever, you have to make some internal computation in a solidity function with the help of an array, try to use memory arrays instead of storage. By default creating an array means storage location however if you know exactly the size of the array and you do not want to use "push" operator, you can use fixed size memory arrays.

function testStorage(){
    uint[100] i;
    i[1] = 1;
    i[2] = 2;
    i[3] = 3;
}

function testMemory(){
    uint[100] memory i;
    i[1] = 1;
    i[2] = 2;
    i[3] = 3;

As in "testStorage" each new value adding associated to the array cost about 20.000 gas, in the "testMemory" example accessing the values of the array practically does not cost anything.