Course contentsShow
← Software Engineering
Lesson 948 of 1,93329. Object-Relational MappingFree lesson

Write Performance and Batch Operations

Optimizing ORM write performance through batching, bulk operations, and understanding when to bypass the ORM for inserts/updates.

Write Performance and Batch Operations

You'll learn how to dramatically speed up database writes by understanding when to batch, bulk, or bypass your ORM entirely.

The Problem

ORMs are fantastic for reading and mapping objects, but they can become bottlenecks during writes. Each insert or update typically triggers individual SQL statements, network round-trips, and object-state tracking overhead. When saving 1,000 records one-by-one, you're making 1,000 separate database calls—that's painfully slow.

Core Optimization Strategies

Batching groups multiple operations into a single transaction, reducing round-trips. Instead of committing after every insert, you accumulate changes in your Unit of Work and flush them together.

Bulk operations skip the ORM's object tracking entirely, issuing optimized SQL directly. Rather than loading 10,000 objects into memory, tracking their state, and updating them individually, you execute one UPDATE statement that affects all matching rows.

Bypassing the ORM means writing raw SQL for specific operations. When you need to insert thousands of rows, a raw INSERT ... VALUES or database-specific bulk loader (like PostgreSQL's COPY) runs orders of magnitude faster than object mapping.

When to Use Each Approach

  • Use batching for moderate-scale writes (dozens to hundreds) where you still need object validation and relationships
  • Use bulk operations for large-scale updates/deletes based on criteria, not individual objects
  • Bypass the ORM for imports, migrations, or anything processing thousands+ rows where object behavior isn't needed

Think of it like cooking: individual gourmet meals (normal ORM) versus meal prep (batching) versus industrial food processing (bulk/raw SQL). Each has its place.

Key Takeaway: ORM write performance improves dramatically through batching in transactions, bulk operations for set-based updates, and strategic raw SQL for high-volume inserts—choose based on scale and whether you need object-level logic.