2

Iteration uses a lot of gas. I was thinking at different options I could minimise the costs. I must understand why one thing doesn't work: Why can't I push into an array using multiplication rather than loops?

For example, this code works:

address[] contenders

for (int i; i<5;i++)
        contenders.push(msg.sender);

This code doesn't:

address[] contenders
uint numberToMultiply  /// let's say this variable is 5

contenders.push(msg.sender) * numberToMultiply

Basically in the last example I am expecting to push msg.sender in the array by the number of times stored in the variable.

Would it not be gas efficient? Furthermore, it doesn't work. Does anyone know the reason?

2 Answers 2

3

I'm not sure if that kind of construct would work in any language (none that I know of) but I also fail to see what would be the point. I can't see many situations where someone would want to push the same value multiple times into an array. Maybe something like initializing an array with all true boolean values.

Because commands are executed from left to right, the contenders.push(msg.sender) is executed first. It returns the new length of the array (What is the return of array.push() in Solidity?). Therefore you are trying to execute something like "number * 5", which actually should give you a result if you store it in a variable - but it's not executing anything except the calculation.

2
  • 1
    [OT] in Python you can write something like this a = [1]*27
    – Briomkez
    Commented Sep 14, 2018 at 18:50
  • Exactly. It's because I'm coming from python so that's why I thought it would work this way. Thanks all for the answers. I make sure to leave a big up for you all
    – Iulian
    Commented Sep 14, 2018 at 19:25
1

The code doesn't work because it was not designed to work that way. You are missing the concept.

From solidity documentation

push: Dynamic storage arrays and bytes (not string) have a member function called push that can be used to append an element at the end of the array. The function returns the new length.

Array.push return new length of the array. So multiplying it by 5 won't insert the data 5 times.

1
  • Thanks for the information. I was thinking if the language had this functionality like Python but seems to not.
    – Iulian
    Commented Sep 14, 2018 at 19:27

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.