0
pragma solidity ^0.4.24;
contract test{
    uint[] public array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
    function removewithgap(uint index)  returns(uint[]) {
        if (index >= array.length) return;
        delete array[index];
        return array;
    }
    function removewithoutgap(uint index)  returns(uint[]) {
        if (index >= array.length) return;

        for (uint i = index; i<array.length-1; i++){
            array[i] = array[i+1];
        }
        delete array[array.length-1];
        array.length--;
        return array;
    }
}

When I am using removewithgap function my transaction cost is kind os normal. But when I use removewithoutgap function my transaction cost increases exponentially as the length of my array grows. Is there any efficent way to remove the element without gap?

  • 2
    Do you care about the order of elements? – goodvibration May 22 at 11:41
  • 1
    BTW, with regards to increases exponentially, I believe that you mean increases linearly. – goodvibration May 22 at 11:42
0

Well, it's always costly when you want to perform the delete operation on an array in solidity. But I found a little bit more efficient manner to resolve this problem.

pragma solidity >=0.5.0 <0.7.0;
contract deletefromarray{
uint[] array;
mapping(uint=>uint) indexOfValue;

function removeWithoutGap(uint _valueToDelete) public {
    uint index = indexOfValue[_valueToDelete];
        if (index >= array.length) return;

        if (array.length > 1) {
        array[index] = array[array.length-1];
        }
        array.length--; 
    }
}

it just refunds gas setting non-zero storage values to zero again. It's a little cheaper than explicitly saying delete array[index]

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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