{{ message }}

Instantly share code, notes, and snippets.

Created Oct 24, 2018
An unoptimized solidity contract
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 pragma solidity ^0.4.25; contract Unoptimized { bool oftenTrue = true; bool oftenFalse = false; uint loops = 0; string greeting = 'Hello World'; function shortCircuit() public view returns(bool){ if (oftenFalse || oftenTrue) { return true; } } function shortCircuit2() public view returns(bool){ if(oftenTrue && oftenFalse) { return false; } else { return true; } } function looping (uint x) public returns (bool) { for(uint i; i < x; i++){ loops += 1; } return true; } function looping2 (uint x) public pure returns(bool){ uint m = 0; uint v = 0; for(uint i = 0; i < x; i++){ m += i; } for(uint j = 0; j < x; j++){ v -= j; } return true; } function looping3 (uint x, uint y) public pure returns(uint){ for(int i = 0; i < 100; i++){ if(x > 0){ y += x; } } return y; } function byteArray() public returns(uint){ byte[] byteArray; return gasleft(); } }

### crytpo-nik commented Oct 7, 2021

in function 'looping' we do not need a loop we can simply x + loops and save gas.
in function ' looping2' we don not need loops, we can set simply say " m = [(i+1)/2] *I "
for the 'looping3' we just need an if and instead of using a loop we can simply say " y = 100x"

### akerbabber commented Oct 13, 2021

The function 'looping' can be modified using a memory variable declared inside the function's scope.
` function auxlooping (uint x) public returns (bool) { uint auxLoops = 0; for(uint i; i < x; i++){ auxLoops += 1; } loops = auxLoops; return true; }`
We could also delete the for loop and just add x to loops, but I don't know if the exercise intended this.

In 'looping2', we can merge the two loops since they make the same number of iterations

In 'looping3' we can move the if statement outside the loop since the value of 'x' is not modified inside the loop.

'byteArray' could use a reduced byte size, since arrays get packed in solidity it is useful to declare smaller types.