String แบบ Immutable (ไม่สามารถเปลี่ยนแปลงได้)
คลาส String ใน C# เป็น Immutable หมายความว่าทุกครั้งที่ทำการเปลี่ยนแปลงค่า String จะสร้างอ็อบเจ็กต์ใหม่ในหน่วยความจำ ทำให้ String เดิมไม่ถูกแก้ไขโดยตรง
ตัวอย่าง String (Immutable)
string str = "Hello";
str = str + " World"; // สร้างอ็อบเจ็กต์ใหม่ ทิ้งอันเก่า
ตัวอย่างโค้ดเปรียบเทียบ String
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str1 = "Steve";
string str2 = "Ben";
if (String.Compare(str1, str2) == 0) {
Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
} else {
Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
}
Console.ReadKey();
}
}
}
String แบบ Mutable (สามารถเปลี่ยนแปลงได้) - StringBuilder
คลาส StringBuilder เป็น Mutable String สามารถขยายจำนวนตัวอักษรได้โดยไม่สร้างอ็อบเจ็กต์ใหม่ในหน่วยความจำ เหมาะสำหรับการต่อสตริงหลายครั้ง
การประกาศ StringBuilder
StringBuilder str = new StringBuilder();
ตัวอย่างการใช้งาน StringBuilder
using System;
using System.Text;
public class Program {
public static void Main() {
StringBuilder str = new StringBuilder("Web World!!", 30);
str.Replace("World", "Arena");
Console.WriteLine(str); // ผลลัพธ์: Web Arena!!
}
}
ตารางเปรียบเทียบสรุป
| คุณสมบัติ | String (Immutable) | StringBuilder (Mutable) |
|---|---|---|
| การเปลี่ยนแปลงค่า | สร้างอ็อบเจ็กต์ใหม่ทุกครั้ง | แก้ไขในอ็อบเจ็กต์เดิม |
| ประสิทธิภาพหน่วยความจำ | ต่ำ (เมื่อต่อสตริงหลายครั้ง) | สูง (เหมาะสำหรับการต่อสตริงซ้ำ) |
| Thread Safety | ปลอดภัย (Immutable) | ไม่ปลอดภัย (ต้องใช้ lock เอง) |
| เหมาะสำหรับ | สตริงคงที่ เปลี่ยนแปลงน้อย | สตริงที่ต่อ/แก้ไขบ่อย |
แนวทางการเลือกใช้งาน
- ใช้ String สำหรับข้อความคงที่ การเปรียบเทียบ และการใช้งานทั่วไป
- ใช้ StringBuilder เมื่อต้องต่อสตริงในลูป หรือสร้างข้อความยาวๆ แบบ Dynamic