String trong C# là immutable — khi tạo ra thì không bao giờ thay đổi.
- Các thao tác như
string.Replace()tạo ra chuỗi mới chứ không sửa chuỗi cũ. - Tính immutable đảm bảo thread-safety và cho phép string interning (tối ưu bộ nhớ bằng cách tái dùng chuỗi giống nhau).
- Tuy nhiên việc ghép chuỗi trong vòng lặp sẽ tốn nhiều bộ nhớ — hãy dùng
StringBuilderthay thế.
Strings are immutable — once created, they never change.
- Operations like
string.Replace()create new strings rather than modifying existing ones. - Immutability ensures thread-safety and enables string interning (memory optimization).
- However, concatenating strings in loops is expensive — use
StringBuilderinstead.