Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เคล็ดลับเพิ่มประสิทธิภาพโค้ด C# (Optimization Tips)

การเพิ่มประสิทธิภาพ (Optimization) ควรทำหลังจากมี Profiling Data จริง — "Premature optimization is the root of all evil" (Donald Knuth)

เคล็ดลับที่มีผลจริง

1. เลือก Collection ให้เหมาะสม

สถานการณ์แนะนำหลีกเลี่ยง
เพิ่ม/ลบบ่อย, ไม่รู้ขนาดล่วงหน้าList<T>ArrayList (Non-generic, Boxing)
ขนาดคงที่, Random Access บ่อยArray T[]List<T> (Overhead)
Key-Value LookupDictionary<TKey, TValue>List<T> + Loop
Unique ItemsHashSet<T>List<T> + Contains
Queue/FIFOQueue<T>List<T> + RemoveAt(0)

2. หลีกเลี่ยง Boxing/Unboxing

// ❌ ร้าย: Boxing ทุกครั้ง
ArrayList list = new ArrayList();
list.Add(10); // int → object

// ✅ ดี: Generic ไม่ Boxing
List list = new List();
list.Add(10); // int อยู่ใน Stack โดยตรง

3. String Concatenation ใน Loop

// ❌ ร้าย: สร้าง String ใหม่ทุกรอบ (Immutable)
string s = "";
for (int i = 0; i < 1000; i++) s += i.ToString();

// ✅ ดี: StringBuilder
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.Append(i);
string result = sb.ToString();

// ✅ ดีกว่า (C# 8+): string.Join
string result = string.Join("", Enumerable.Range(0, 1000).Select(i => i.ToString()));

4. Struct vs Class

  • Struct (Value Type): เก็บบน Stack, ไม่มี GC Pressure, เหมาะสำหรับข้อมูลเล็ก Immutable (Point, DateTime, Guid)
  • Class (Reference Type): Heap, GC, เหมาะสำหรับ Object ใหญ่/ซับซ้อน/ต้องการ Polymorphism

5. Span<T> / Memory<T> (C# 7.2+)

หลีกเลี่ยงการ Allocate Array ใหม่เมื่อ Slice/Substring:

// ❌ Allocate ใหม่
byte[] sub = original.Skip(10).Take(5).ToArray();

// ✅ Zero-allocation View
Span slice = original.AsSpan(10, 5);

6. คำนวณค่าคงที่ (Constant Folding)

// Compiler คำนวณให้ทุกตอน Compile
const int SecondsPerDay = 24 * 60 * 60; // = 86400

// ใช้ const สำหรับค่าที่ไม่เปลี่ยนแปลง
// ใช้ readonly สำหรับค่าที่ตั้งค่าตอน Runtime (Constructor)

สิ่งที่ไม่ควรทำ (Micro-optimizations ที่ไม่คุ้มค่า)

  • ❌ ใช้ for แทน foreach ทุกกรณี (foreach เร็วพอในกรณีส่วนใหญ่)
  • ❌ ใช้ Bit Shift (<<, >>) แทน คูณ/หาร 2^n — Compiler ทำให้อัตโนมัติ
  • ❌ ประกาศ Variable นอก Loop เพื่อ "ประหยัด Memory" — JIT จัดการให้แล้ว

เครื่องมือวัดประสิทธิภาพ

  • BenchmarkDotNet — Gold Standard สำหรับ Micro-benchmarking
  • dotnet-trace / PerfView — CPU/Memory Profiling
  • Visual Studio Profiler — Built-in, ใช้ง่าย