Created
May 17, 2018 14:03
-
-
Save critesjosh/2dc25da9d96a4f830c5874932a6b4c6f to your computer and use it in GitHub Desktop.
Optimizations to the Unoptimized.sol 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.0; | |
contract Optimized { | |
bool oftenTrue = true; | |
bool oftenFalse = false; | |
uint loops = 0; | |
bytes32 constant statictext = "Hello world"; | |
// Remove unnecessary code | |
// reduces costs of deploying the contract | |
function p1(uint x) public pure returns(bool) { | |
if(x > 5) | |
return true; | |
} | |
// Reduce expensive operations | |
// Take advantage of short circuiting rules | |
function shortCircuit() public view returns(bool){ | |
if(oftenTrue || oftenFalse){ //The operators || and && apply the common short-circuiting rules. | |
return true; //This means that in the expression f(x) || g(y), if f(x) evaluates | |
} //to true, g(y) will not be evaluated even if it may have side-effects. | |
} | |
function shortCircuit2() public view returns(bool){ | |
if(oftenFalse && oftenTrue){ // In the AND conditional, if the first condition evaluates | |
return false; // to false, the second condition is not evalutated, saving gas. | |
} else { // Put the conidtion that is more likely to be false first in the | |
return true; // conidtion check | |
} | |
} | |
// Remove expensive operations from the loop | |
function looping(uint x) public returns (bool){ | |
uint total = 0; | |
for(uint i; i < x; i++){ | |
total += 1; | |
} | |
loops += total; // only reads and writes to storage 1 time | |
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; | |
v -= i; | |
} | |
return true; | |
} | |
// Hint: Minimal code in a loop | |
function looping3(uint x, uint y) public pure returns(uint){ | |
if (x <= 0) return y; // The x check does not need to be in the | |
for(int i = 0; i < 100; i++){ // loop. Save gas by putting outside | |
y += x; | |
} | |
return y; | |
} | |
// Use of fixed size byte arrays | |
function bytesArray() public view returns(uint){ | |
bytes bytesArray; // Using type bytes instead of type byte[] is more efficient | |
return gasleft(); | |
} | |
function getString() public pure returns(bytes32){ | |
return statictext; // statictext is now type bytes32 rather than string | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment