#StackBounty: usedGas comparison: `push()` a struct into the array vs change all the values on the same struct that is stored in the array

Bounty: 50

[Q] When I push() a new struct into an array vs. when change all the values inside the same struct that is stored in the array, they both consume different usedGas. Regarding this difference, which path should I take, in order to use gas efficiently:

node[] array_1;
function foo(){
    array_1.push(<some_value>);
}

or

uint32 index=0;
node[<array_size>] array_2;
function foo() {
   array_2[index++].value = <some_value>;
}

[Observation] When I push() a new struct into my array, it uses much less gas than when I change all the values inside the same struct that is stored in the array.

Why do they differ on gas usage since both do the same operations? I assume, I am doing something wrong.

https://github.com/ethereum/wiki/wiki/Solidity-Features:

.push() for Dynamic Storage Arrays
PT Dynamically-sized storage arrays have a member function push, such
that var l = arr.push(el); is equivalent to arr[arr.length++] = el;
var l = arr.length;.

In this following example: you could see the different gas usage.

my_contract.transact().push_me( 30, 40, 16 ); consumes 63146 gas
my_contract.transact().change( 30, 40, 16 );  consumes 79468 gas

contract Example {
  struct node { 
    uint32 blk_start;
    uint32 blk_end;
    uint16 core;
    uint32 next; 
   }
   node[]    array_1;
   node[10]  array_2;
   uint32 index = 0;

   function push_me( uint32 blk_start_, uint32 blk_end_, uint16 core_ ) {
     array_1.push(node( { blk_start: blk_start_, blk_end: blk_end_, core: core_, next: 10 }));
   }

   function change( uint32 blk_start_, uint32 blk_end_, uint16 core_ ) {
     array_2[index].core       = core_;
     array_2[index].blk_start = blk_start_;
     array_2[index].blk_end   = blk_end_;
     array_2[index].next      = 10;
     index++;
   }
}

Thank you for your valuable time and help.


Get this bounty!!!

Leave a Reply