ADO - ADO.NET Performance Tuning & Profiling
1. What performance tuning actually means
Improving latency, throughput, and resource usage of data access by:
-
Reducing round trips
-
Reducing CPU & memory usage
-
Using the database efficiently
Profiling = measuring before fixing.
2. Biggest performance killers (facts)
| Issue | Impact |
|---|---|
| Opening connections repeatedly | High latency |
| Missing parameters | No plan reuse |
| Row-by-row operations | Extremely slow |
| Over-fetching columns | Memory waste |
| Long transactions | Blocking & deadlocks |
3. Connection-level tuning (critical)
Use pooling (default)
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
}
✔ Always close connections
✔ Never keep global connections
✔ Standardize connection strings
4. Command-level tuning
Always parameterize
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
Benefits:
-
Query plan reuse
-
Reduced CPU
-
Injection-safe
5. Use the right execution API
| Scenario | Best API |
|---|---|
| Read-only, forward-only | SqlDataReader |
| Bulk insert | SqlBulkCopy |
| Disconnected updates | DataAdapter |
| Scalar value | ExecuteScalar() |
Wrong API = wasted resources
6. Reduce data transfer
❌
SELECT * FROM Orders
✔
SELECT OrderId, Amount FROM Orders
✔ Faster network
✔ Less memory
✔ Faster GC
7. Batch & bulk wisely
-
Use batch updates for UPDATE/DELETE
-
Use SqlBulkCopy for INSERT
-
Tune
BatchSize(50–500)
Never loop inserts unless unavoidable.
8. Transaction tuning
✔ Keep transactions short
✔ Choose correct isolation level
✔ Avoid long-running transactions
Bad:
tx.Begin();
// UI + DB logic
tx.Commit();
9. Profiling tools (what to actually use)
Application side
-
Stopwatch -
.NET profilers (dotTrace, PerfView)
-
Logging SQL execution time
Database side
-
Execution plans
-
Query Store
-
Index usage stats
Rule:
If you don’t measure it, you’re guessing.
10. Detecting bottlenecks
Checklist:
-
Is DB CPU high? → bad queries
-
Is app CPU high? → mapping / loops
-
High waits? → locks or IO
-
Timeouts? → pool exhaustion or slow SQL
11. Common tuning mistakes
❌ Premature optimization
❌ Blaming DB without profiling
❌ Using ORM defaults blindly
❌ Increasing timeouts instead of fixing root cause
12. Real-world tuning order (important)
-
Measure
-
Fix SQL
-
Reduce data
-
Batch/bulk
-
Tune transactions
-
Tune connection usage