For SQLite3 performance optimization on HDD (hard disk drives), here are the key strategies:
Write Performance Optimizations
Use transactions for bulk operations - This is crucial on HDDs since each commit causes a disk sync:
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for _, item := range items {
_, err = tx.Exec("INSERT INTO table VALUES (?)", item)
if err != nil {
return err
}
}
return tx.Commit()
Adjust PRAGMA settings for HDD-specific optimizations:
// Reduce sync frequency (trade-off: less durability)
db.Exec("PRAGMA synchronous = NORMAL") // or OFF for maximum speed
// Increase cache size to reduce disk reads
db.Exec("PRAGMA cache_size = -64000") // 64MB cache
// Use WAL mode for better concurrency
db.Exec("PRAGMA journal_mode = WAL")
// Increase page size for sequential access
db.Exec("PRAGMA page_size = 8192") // Must be set before creating tables
Read Performance Optimizations
Create appropriate indexes - HDDs have high seek times, so indexes are critical:
db.Exec("CREATE INDEX idx_user_email ON users(email)")
db.Exec("CREATE INDEX idx_orders_date ON orders(created_at)")
Use prepared statements to reduce parsing overhead:
stmt, err := db.Prepare("SELECT * FROM users WHERE id = ?")
if err != nil {
return err
}
defer stmt.Close()
// Reuse the prepared statement
for _, id := range userIDs {
row := stmt.QueryRow(id)
// Process row
}
HDD-Specific Considerations
Minimize random I/O by:
- Clustering related data together using INTEGER PRIMARY KEY for natural ordering
- Using VACUUM periodically to defragment the database file
- Keeping the database file on a dedicated partition to reduce fragmentation
Connection pooling with appropriate settings:
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
Consider memory-mapped I/O:
db.Exec("PRAGMA mmap_size = 268435456") // 256MB memory map
The most impactful optimizations for HDD are using transactions for writes, enabling WAL mode, and ensuring proper indexing. These reduce the number of disk seeks and syncs, which are the primary bottlenecks on spinning disks.