Gas Optimization in Solidity

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Day 23: Gas Optimization in

Solidity: Constant vs.


Immutable

When working with Solidity, optimizing gas usage is a

critical part of smart contract development. Two

powerful tools for this optimization are the constant and

immutable keywords. They enable developers to store

certain variables directly in the bytecode of the contract

instead of in storage, which can lead to significant gas

savings. In this article, we’ll delve into these keywords,

explore their benefits, and highlight the scenarios

where each should be used.


What Are Constant and Immutable Variables?

Constant Variables
A constant variable is one whose value is assigned at

compile time and never changes throughout the lifetime

of the contract. These variables are particularly useful

for defining fixed values, such as mathematical

constants or configuration parameters.

Key Features

● Compile-time assignment: The value must be

known and set when the contract is compiled.

● Gas efficiency: constant variables do not occupy a

storage slot, as their values are embedded

directly in the bytecode.

● Readability: Constants make code easier to

understand and maintain.


Example:

// Without constant

uint256 public MINIMUM_USD = 5e18;

// With constant

uint256 public constant MINIMUM_USD = 5e18;

Gas Savings:

When you declare a variable as constant, it removes the

need for a storage slot. For instance, converting

MINIMUM_USD to constant reduced deployment costs in a test

contract from 859,000 gas to 840,000 gas.

Naming Convention:

By convention, constant variables are written in

uppercase with underscores separating words. This

makes them easily distinguishable from other variables.

Immutable Variables
An immutable variable is one that is assigned once during

the execution of the constructor and cannot be modified

afterward. Unlike constants, their value does not need

to be known at compile time but is still set only once.

Key Features

● Assigned in constructor: immutable variables can

be initialized based on logic or runtime

conditions.

● Gas efficiency: Like constants, immutable

variables are embedded in the bytecode and do

not use storage slots.

● Flexibility: They allow dynamic initialization,

making them ideal for values that depend on

runtime inputs.

Example:

// Without immutable
address public owner;

// With immutable

address public immutable i_owner;

constructor() {

i_owner = msg.sender; // Set the deployer's address

Gas Savings:

Using an immutable variable instead of a regular state

variable avoids the need for a storage write during

initialization, reducing deployment costs.

Naming Convention:

By convention, immutable variables are often prefixed

with i_ to differentiate them from other variables.

Why Do These Keywords Save Gas?


In Solidity, regular state variables are stored in storage

slots, which are the most expensive form of data storage


in the Ethereum Virtual Machine (EVM). When you

declare a variable as constant or immutable:

1. The variable’s value is embedded directly in the

contract’s bytecode.

2. No storage slots are used, reducing deployment

and access costs.

3. Reads from bytecode are much cheaper than

reads from storage.

Comparing Constant and Immutable


Feature: Assignment Timing

● Constant: Compile-time

● Immutable: Constructor (runtime)

Feature: Flexibility
● Constant: Fixed values only

● Immutable: Can depend on runtime logic

Feature: Gas Efficiency

● Constant: Saves storage slot

● Immutable: Saves storage slot

Feature: Use Case

● Constant: Unchanging values (e.g., constants)

● Immutable: Set-once values (e.g., contract

owner)

Feature: Example Value

● Constant: uint256 constant MINIMUM_USD = 5e18;

● Immutable: address immutable i_owner = msg.sender;


Scenarios and Examples

When to Use Constant


Use constant for values that are known and fixed at

compile time, such as:

● Mathematical constants (e.g., PI = 3.14159)

● Immutable configuration parameters (e.g.,

TOKEN_NAME, TOKEN_DECIMALS)

Example:

uint256 public constant MAX_SUPPLY = 1_000_000 * 1e18;

When to Use Immutable


Use immutable for values that:
● Depend on runtime inputs (e.g., the deployer’s

address, a timestamp, or a contract address).

● Must not be changed after initialization.

Example:

address public immutable i_admin;

constructor(address _admin) {

i_admin = _admin;

Benefits of Using Constant and Immutable


1. Gas Cost Savings:

● Avoid storage costs for state variables.

● Reduce both deployment and runtime costs.

2. Security:
● Prevent accidental modifications by enforcing

immutability.

3. Code Clarity:

● Improve readability by explicitly signaling that

certain values cannot change.

Conclusion
In Solidity, using constant and immutable is a best practice

for optimizing gas costs and ensuring the integrity of

fixed values. While constant is ideal for compile-time

fixed values, immutable provides flexibility for values

determined at deployment. By understanding and

applying these tools effectively, developers can write

more efficient and secure smart contracts.

Further Exploration
Experiment with these keywords in your contracts and

measure gas savings. Tools like Remix, Hardhat, or

Foundry can help you analyze gas consumption during

deployment and execution.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy