Skip to content

Instantly share code, notes, and snippets.

@ConsenSys-Academy
Created October 24, 2018 17:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ConsenSys-Academy/a61670fd8796d73d8b4b7d5935f9e714 to your computer and use it in GitHub Desktop.
Save ConsenSys-Academy/a61670fd8796d73d8b4b7d5935f9e714 to your computer and use it in GitHub Desktop.
An unoptimized solidity contract
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();
}
}
@akerbabber
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment