0

Is it possible to reduce the gas cost of this function? It's currently at 140k gas for 20 elements. (I'm new to solidity)

uint8[1000] public array;

function Test(uint32[] index, uint8[] value) public  {        
    for (uint i=0; i<index.length; i++) {
        array[index[i]] = value[i];
    }
}

1 Answer 1

0

Have you tried creating a mapping of the index and the value instead of creating two separate arrays? It would work in certain situations but this code doesn`t tell me anything.

//Creating the mapping:
mapping(uint32 index => uint8 value) theMap;
//Then when setting the value:
theMap[index] = value;
//Then to get it back:
uint8 value = theMap[index]
2
  • Thanks for the suggestion Gabe. I need a function to return the entire array so I don't think a mapping will work, right? I think I'll just have to accept the high gas cost. Mar 7, 2018 at 13:42
  • I would look at this post to see what would fit you best: ethereum.stackexchange.com/questions/13167/…. You have to be really careful when looping since you can hit your gas limit extremely fast. Keep in mind that looping while doing payments is also something that should be avoided at all cost (use the withdrawal pattern for that).
    – Gabe
    Mar 9, 2018 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.