Skip to content

Instantly share code, notes, and snippets.

@critesjosh
Last active May 17, 2018 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save critesjosh/0c7ca75d28ab0fdf89642e2f6b52acda to your computer and use it in GitHub Desktop.
Save critesjosh/0c7ca75d28ab0fdf89642e2f6b52acda to your computer and use it in GitHub Desktop.
An unoptimized solidity contract
pragma solidity ^0.4.0;
contract Unoptimized {
bool oftenTrue = true;
bool oftenFalse = false;
uint loops = 0;
string greeting;
bytes32 greeting1;
function p1(uint x) public pure returns(bool) {
if(x > 5)
if(x*x < 20){
return false;
} else {
return true;
}
}
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;
}
}
// Hint: Remove expensive operations from the loop
function looping(uint x) public returns (bool){
for(uint i; i < x; i++){
loops += 1;
}
return true;
}
// Hint: Reduce number of loops
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;
}
// Hint: Minimal code in a loop
function looping3(uint x, uint y) public pure returns(uint){
for(int i = 0; i < 100; i++){
if(x > 0){
y += x;
}
}
return y;
}
// Use of fixed size byte arrays
// Relevant Solidity docs:
// https://solidity.readthedocs.io/en/latest/types.html#fixed-size-byte-arrays
function byteArray() public returns(uint){
byte[] byteArray;
return gasleft();
}
function limitedStringLength(string x) public returns(string){
greeting = x;
return greeting;
}
function limitedStringLength1(bytes32 x) public returns(bytes32){
greeting1 = x;
return greeting1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment