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];
    }
}
Richard Horrocks
  • 37,835
  • 13
  • 87
  • 144

1 Answers1

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]
Gabe
  • 363
  • 1
  • 11
  • 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. – Joost Vanhoutte Mar 07 '18 at 13:42
  • I would look at this post to see what would fit you best: https://ethereum.stackexchange.com/questions/13167/are-there-well-solved-and-simple-storage-patterns-for-solidity?noredirect=1&lq=1. 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 09 '18 at 10:11