pragma solidity ^0.4.24; contract GasOptimization { /* SLOAD opcode which reads a data word from storage costs 200 gas. MSTORE and MLOAD opcodes which writes and reads a data word from memory costs 3 gas each. As such, it is much more efficient to declare to memory if used multiple times in function logic. */ uint256 public num; constructor() public { num = 50; } function readStorage() public { if (num == 40 || num <= 10 && num > 100) { // execution cost: 885 gas } } function readMemory() public { uint256 mnum = num; if (mnum == 40 || mnum <= 10 && mnum > 100) { // execution cost: 605 gas } } /* SSTORE opcode which writes a data word to storage costs 20000 gas + some amount depending on the type. SLOAD opcode which reads a data word from storage costs 200 gas + some amount depending on the type. Intuition would tell us gas optimizations can be acheived by using smaller data types. However this is only the case inside of structs. Long type should be used unless struct packing is possible. */ uint256 public integer256; function write() public { integer256 = 1; // 20430 gas } function read() public returns (uint256) { return integer256; // 656 gas } uint128 public integer128; function write() public { integer128 = 1; // 20648 gas } function read() public returns (uint128) { return integer128; // 671 gas } /* struct PackedStruct { uint128 num1; uint128 num2; } equiv struct PackedStruct { uint256 num; } */ struct Struct256 { uint256 num; } Struct256 public struct256; function write() public { struct256 = Struct256(1); // 20497 gas } function read() public returns (uint256) { return struct256.num; // 678 gas } struct Struct256 { bytes32 num1; bytes32 num2; } Struct256 public struct256; function write() public { struct256 = Struct256(1,2); // 40527 gas } function read() public returns (bytes32,bytes32) { return (struct256.num1,struct256.num1) ; // 708 gas } }
0.4.24