Efficient data structures help store and manage data quickly and save space. This is very important in blockchain because every byte and operation costs money and time.
0
0
Efficient data structures in Blockchain / Solidity
Introduction
When you need to store transaction records in a way that is fast to access and verify.
When you want to keep track of account balances without using too much storage.
When you need to quickly check if a piece of data exists on the blockchain.
When you want to organize smart contract data to reduce gas fees.
When you want to build a blockchain application that handles many users efficiently.
Syntax
Blockchain / Solidity
struct DataStructureName {
// fields to store data
};
mapping(KeyType => ValueType) public dataMap;
// Example: Using arrays, mappings, structs, or trees depending on needIn blockchain, common data structures include mappings (like dictionaries), arrays, and structs to organize data.
Choosing the right data structure can save gas fees and speed up your smart contract.
Examples
This example shows a struct to hold user data and an array to store many users.
Blockchain / Solidity
struct User {
uint id;
string name;
}
User[] public users;This mapping stores the balance for each user address. It is fast to look up and update.
Blockchain / Solidity
mapping(address => uint) public balances;
This mapping helps quickly check if some data (identified by a hash) exists on the blockchain.
Blockchain / Solidity
mapping(bytes32 => bool) public dataExists;Sample Program
This smart contract uses a struct and an array to store users and a mapping to store balances. It shows how to add users and check balances efficiently.
Blockchain / Solidity
pragma solidity ^0.8.0; contract EfficientData { struct User { uint id; string name; } User[] public users; mapping(address => uint) public balances; function addUser(uint _id, string memory _name) public { users.push(User(_id, _name)); balances[msg.sender] = 100; } function getUserCount() public view returns (uint) { return users.length; } function getBalance(address user) public view returns (uint) { return balances[user]; } }
OutputSuccess
Important Notes
Mappings do not store keys, so you cannot iterate over them directly.
Arrays allow iteration but can be costly if they grow too large.
Structs help group related data together for clarity and efficiency.
Summary
Efficient data structures save space and gas in blockchain apps.
Use mappings for fast lookups by key.
Use structs and arrays to organize complex data.