Solana Program Optimization Techniques
Optimizing Solana programs is crucial for reducing costs and improving performance. This guide covers compute units, memory management, account serialization, and performance best practices.
Compute Units
Every Solana transaction has a compute budget measured in Compute Units (CU). Understanding and optimizing CU usage is essential.
Compute Budget
use anchor_lang::prelude::*;
#[program]
pub mod compute_example {
use super::*;
pub fn efficient_operation(ctx: Context<EfficientOp>) -> Result<()> {
// Use compute budget instruction to set limits
let ix = anchor_lang::solana_program::compute_budget::ComputeBudgetInstruction::set_compute_unit_limit(200000);
let transaction = anchor_lang::solana_program::system_instruction::new_instruction(&ix);
Ok(())
}
}
#[derive(Accounts)]
pub struct EfficientOp<'info> {
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
CU Optimization Strategies
| Strategy | CU Savings | Description |
|---|---|---|
| Reuse accounts | 10-20% | Avoid duplicate account loading |
| Minimize CPI calls | 20-30% | Reduce cross-program invocations |
| Use unchecked accounts | 5-10% | Skip unnecessary constraints |
| Batch operations | 15-25% | Process multiple items in one tx |
| Avoid realloc | 10-15% | Minimize account resizing |
CU Measurement
// Measure CU usage at specific points
msg!("CU before: {}", anchor_lang::solana_program::sysvar::clock::Clock::get()?.unix_timestamp);
// Your computation here
msg!("CU after: {}", anchor_lang::solana_program::sysvar::clock::Clock::get()?.unix_timestamp);
Memory Management
Efficient memory usage reduces costs and improves performance.
Account Size Optimization
#[account]
pub struct OptimizedAccount {
pub data: Vec<u8>, // Variable length
pub count: u32, // Compact counter
pub flags: u8, // Bit flags for status
// Use Option<T> for optional data
pub optional_data: Option<[u8; 32]>,
}
impl OptimizedAccount {
// Calculate optimal size
pub fn calculate_size(data_len: usize) -> usize {
8 + // Discriminator
4 + data_len + // Vec<u8> with length prefix
4 + // u32 count
1 + // u8 flags
1 + 32 // Option<[u8; 32]>
}
}
Serialization Optimization
// Use borsh for efficient serialization
use borsh::{BorshSerialize, BorshDeserialize};
#[derive(BorshSerialize, BorshDeserialize)]
pub struct CompactData {
pub small_num: u8, // 1 byte instead of 8
pub compact_string: String, // Length-prefixed
pub fixed_array: [u8; 32], // Fixed size
}
// Avoid unnecessary cloning
pub fn process_data(data: &CompactData) -> Result<()> {
// Use references instead of cloning
let value = data.small_num;
Ok(())
}
Memory Allocation Patterns
// Pre-allocate when possible
pub fn batch_process(items: Vec<Item>) -> Result<()> {
let mut results = Vec::with_capacity(items.len()); // Pre-allocate
for item in items {
results.push(process_item(item)?);
}
Ok(())
}
// Use stack allocation for small data
pub fn stack_allocation() {
let buffer = [0u8; 256]; // Stack allocated
// Use buffer...
}
Account Loading Optimization
Efficient Account Loading
use anchor_lang::prelude::*;
#[derive(Accounts)]
pub struct OptimizedAccounts<'info> {
#[account(mut)]
pub user: Signer<'info>,
// Load accounts in order of usage
#[account(mut, seeds = [b"pool"], bump)]
pub pool: Account<'info, Pool>,
// Use has_one for relationships
#[account(mut, has_one = pool)]
pub pool_token_account: Account<'info, TokenAccount>,
// Use constraint for validation
#[account(constraint = user.key() == pool.authority)]
pub authority: Account<'info, TokenAccount>,
}
// Use unchecked accounts when validation is done manually
#[derive(Accounts)]
pub struct UncheckedOptimization<'info> {
#[account(mut)]
pub user: Signer<'info>,
/// CHECK: Manual validation
#[account(mut)]
pub unchecked_account: AccountInfo<'info>,
}
Account Relationship Optimization
// Store references instead of full accounts
#[account]
pub struct StakeRecord {
pub owner: Pubkey, // Reference to user
pub pool: Pubkey, // Reference to pool
pub amount: u64,
pub last_update: i64,
}
// Derive PDAs efficiently
pub fn find_stake_record(user: &Pubkey, pool: &Pubkey) -> (Pubkey, u8) {
Pubkey::find_program_address(
&[
b"stake",
user.as_ref(),
pool.as_ref(),
],
&crate::id(),
)
}
Transaction Optimization
Batch Operations
pub fn batch_transfer(
ctx: Context<BatchTransfer>,
recipients: Vec<(Pubkey, u64)>,
) -> Result<()> {
// Process multiple transfers in one transaction
for (recipient, amount) in recipients {
// Add transfer instruction
}
Ok(())
}
Instruction Parallelization
// Group independent instructions
pub fn parallel_instructions() -> Vec<Instruction> {
let mut instructions = Vec::new();
// These can be parallel
instructions.push(create_account_instruction());
instructions.push(initialize_token_instruction());
// These must be sequential
instructions.push(transfer_instruction());
instructions.push(close_account_instruction());
instructions
}
Transaction Size Limits
| Component | Max Size | Optimization |
|---|---|---|
| Instructions | 1232 bytes | Batch operations |
| Accounts | 64 per tx | Reuse accounts |
| Signers | 64 per tx | Limit signers |
| Data | 10MB per tx | Compress data |
Compute Unit Optimization
CU Reduction Techniques
// Use saturating arithmetic to avoid overflow checks
pub fn safe_add(a: u64, b: u64) -> u64 {
a.saturating_add(b) // No overflow panic
}
// Use checked operations only when needed
pub fn precise_calculation(a: u64, b: u64) -> Option<u64> {
a.checked_mul(b)? // Returns None on overflow
}
// Minimize string operations
pub fn process_name(name: &str) -> Result<()> {
// Avoid unnecessary allocations
let bytes = name.as_bytes();
// Process bytes directly
Ok(())
}
CU Profiling
// Profile different sections
pub fn profile_execution() {
let start = anchor_lang::solana_program::sysvar::clock::Clock::get()?.unix_timestamp;
// Section 1
heavy_computation();
let mid = anchor_lang::solana_program::sysvar::clock::Clock::get()?.unix_timestamp;
msg!("Section 1: {} CU", mid - start);
// Section 2
light_computation();
let end = anchor_lang::solana_program::sysvar::clock::Clock::get()?.unix_timestamp;
msg!("Section 2: {} CU", end - mid);
}
Data Structure Optimization
Compact Data Structures
// Use bit packing for flags
#[derive(BorshSerialize, BorshDeserialize)]
pub struct PackedFlags {
pub bits: u8, // 8 flags in 1 byte
}
impl PackedFlags {
pub fn get_flag(&self, bit: u8) -> bool {
(self.bits & (1 << bit)) != 0
}
pub fn set_flag(&mut self, bit: u8, value: bool) {
if value {
self.bits |= 1 << bit;
} else {
self.bits &= !(1 << bit);
}
}
}
// Use enums for type safety with minimal overhead
#[derive(BorshSerialize, BorshDeserialize, PartialEq)]
pub enum Status {
Active = 0,
Inactive = 1,
Pending = 2,
}
HashMap Alternatives
// Use Vec with index for small datasets
#[account]
pub struct SmallDataset {
pub items: Vec<Item>,
pub index: HashMap<Pubkey, u32>, // Sparse index
}
// For large datasets, use external storage
pub fn process_large_dataset(keys: Vec<Pubkey>) -> Result<()> {
// Process keys in batches
for chunk in keys.chunks(100) {
process_batch(chunk)?;
}
Ok(())
}
Network Optimization
RPC Call Optimization
// Batch RPC calls
async function batchGetAccounts(connection: Connection, addresses: PublicKey[]) {
const accounts = await connection.getMultipleAccountsInfo(addresses);
return accounts;
}
// Use WebSocket for real-time updates
function subscribeToAccount(connection: Connection, address: PublicKey) {
connection.onAccountChange(address, (accountInfo) => {
// Handle update
});
}
Transaction Sending Optimization
// Use skipPreflight for known-good transactions
async function sendOptimizedTransaction(
connection: Connection,
transaction: Transaction,
signers: Keypair[]
) {
const { blockhash } = await connection.getLatestBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = signers[0].publicKey;
transaction.sign(...signers);
// Skip preflight for known-good transactions
const signature = await connection.sendRawTransaction(
transaction.serialize(),
{ skipPreflight: true }
);
return signature;
}
Performance Monitoring
CU Usage Tracking
pub struct CUMetrics {
pub total_cu: u64,
pub cu_per_instruction: Vec<(String, u64)>,
}
impl CUMetrics {
pub fn new() -> Self {
Self {
total_cu: 0,
cu_per_instruction: Vec::new(),
}
}
pub fn track_instruction(&mut self, name: &str, cu: u64) {
self.cu_per_instruction.push((name.to_string(), cu));
self.total_cu += cu;
}
pub fn report(&self) {
msg!("Total CU: {}", self.total_cu);
for (name, cu) in &self.cu_per_instruction {
msg!("{}: {} CU", name, cu);
}
}
}
Performance Benchmarks
| Operation | Target CU | Acceptable Range |
|---|---|---|
| Token Transfer | 5,000 | 4,000 - 8,000 |
| Account Init | 15,000 | 10,000 - 25,000 |
| Complex Logic | 50,000 | 30,000 - 100,000 |
| Full Transaction | 200,000 | 150,000 - 400,000 |
Optimization Checklist
Program Design
- Use appropriate account sizes
- Implement efficient serialization
- Minimize CPI calls
- Use PDA derivation efficiently
- Avoid unnecessary account loading
Memory Management
- Pre-allocate vectors when possible
- Use stack allocation for small data
- Avoid unnecessary clones
- Use references instead of ownership
Transaction Optimization
- Batch independent operations
- Reuse accounts across instructions
- Use compute budget instructions
- Minimize account count
Testing and Profiling
- Profile CU usage
- Test with maximum inputs
- Monitor account sizes
- Benchmark against targets
Trade-offs
Optimization Trade-offs
| Decision | Performance | Cost | Complexity |
|---|---|---|---|
| Batch operations | Higher throughput | Lower fees | More complex |
| Account reuse | Fewer loads | Lower CU | Design constraints |
| Unchecked accounts | Fewer constraints | Lower CU | Safety risk |
| Pre-allocation | Faster execution | More memory | Planning required |
| Saturating math | No panics | Slightly slower | Safe arithmetic |
Size vs Speed
| Factor | Optimize for Size | Optimize for Speed |
|---|---|---|
| Account data | Smaller accounts | More data available |
| Instructions | Fewer instructions | Parallel execution |
| Validation | Minimal checks | Full validation |
| Serialization | Compact format | Fast encoding |
Interview Questions
-
How do compute units affect transaction costs on Solana?
-
Explain the trade-offs between account size and transaction performance.
-
What techniques can reduce CU usage in a Solana program?
Quiz Questions
-
What is the typical CU limit for a Solana transaction?
- a) 10,000
- b) 200,000
- c) 1,000,000
- d) 10,000,000
-
Which technique reduces account loading overhead?
- a) Larger accounts
- b) More accounts
- c) Account reuse
- d) Frequent updates
-
What is the benefit of saturating arithmetic?
- a) Faster execution
- b) No overflow panics
- c) Smaller code size
- d) Better readability
Conclusion
Solana program optimization is essential for building cost-effective, high-performance applications. Understanding compute units, memory management, and transaction optimization enables developers to create efficient programs that scale.