---
# System prepended metadata

title: Gas Effiecient Smart Contract
tags: [note, solidity]

---

# Gas Effiecient Smart Contract

- Do not create contracts 
- Use fixed sized-type variables
    - use bytes32 instead of string or bytes
    - use uint256 instead of uint32
- Minimize the frequency of data storage
  ```
  // Avoid
  function ttt() {
      a = 1;
      b = 2;
      .... // do something
      c = 3;
      d = 4
  }
  
  // better
  function ttt() {
      a = 1;
      b = 2;
      c = 3;
      d = 4;
      ... do something
  }
  ```
  ```
  // LOOP
  uint cnt;
  
  // avoid
  function ttt() {
      for(...) {
          cnt++;
      }
  }
  
  // better
  function ttt() {
      uint tmp = cnt;
      for(...) {
          tmp++;
      }
      cnt = tmp;
  }
  ```
- Data alignment (256 bits)
  ```
  // Avoid
  uint64 a;  --> x1
  uint b     --> x2
  byte c;    -|
  uint64 d;  --> x3
  
  // better
  uint64 a;   -|
  uint64 d;    |
  byte c;     --> x1
  uint b;     --> x2
  ```
- Batch execution
  - gas cost
      - standard tx: 21k
      - external call: 1.4k
  ```
  // avoid
  function ttt(address user);
  
  // better
  function ttt(address[] users);
  ``
- Short circuit rule
  ```
  function a() --> cost 5k
  function b() --> cost 20k
  
  // should
  if (a() || b()) {
      ...
  }
  ```
- Use `external` for functions only accessed externally. (not `public`)
  
### Miscs
- data storage (SSTORE)
  - new: 20k (zero --> nonzero)
  - modify: 5k
  - delete: -15k (actual: -10k (-15k+5k) )
- Instanbul hard fork
    - SLOAD: 200 --> 800
    - BALANCE: 400 --> 700
    - input data: 
        - nonzero: 68 --> 16
        - zero: still 4
- Interesting fact
  ```
  function b() public  --> cost n
  function a() public  --> cost n+22
  ```
  [Function Name Optimization](https://emn178.github.io/solidity-optimize-name/)
  

###### tags `note` `solidity`
