string
和
StringBuilder
类主要在内存管理和字符串操作性能上存在显著区别:
String 类:
StringBuilder 类:
提升性能的使用案例
以下是十个展示 StringBuilder 在性能优化方面应用的示例:
string result = "";
for (int i = 0; i < 10000; i++)
{
// 错误的做法,会生成很多临时字符串
// result += "Item" + i;
// 正确的做法,使用 StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("Item");
sb.Append(i);
result = sb.ToString(); // 只在循环结束后生成最终字符串
}
StringBuilder logBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
logBuilder.Append(data[i].ToString());
logBuilder.Append(",");
}
string logMessage = logBuilder.ToString().TrimEnd(',');
StringBuilder reportBuilder = new StringBuilder();
foreach (var item in reportData)
{
reportBuilder.AppendFormat("ID: {0}, Name: {1}, Value: {2}\n", item.Id, item.Name, item.Value);
}
string report = reportBuilder.ToString();
StringBuilder sqlQuery = new StringBuilder("SELECT * FROM Users WHERE ");
bool isFirst = true;
foreach (var condition in conditions)
{
if (!isFirst)
sqlQuery.Append(" AND ");
sqlQuery.Append($"Column = '{condition}'");
isFirst = false;
}
ExecuteSql(sqlQuery.ToString());
StringBuilder fileContent = new StringBuilder();
using (StreamReader reader = new StreamReader("largeFile.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
fileContent.AppendLine(line);
}
}
string completeFileText = fileContent.ToString();
int[] numbers = Enumerable.Range(1, 10000).ToArray();
StringBuilder numStr = new StringBuilder();
foreach (int number in numbers)
{
numStr.Append(number.ToString());
numStr.Append(",");
}
string numList = numStr.ToString().TrimEnd(',');
StringBuilder emailBody = new StringBuilder(emailTemplate);
emailBody.Replace("{Name}", customer.Name);
emailBody.Replace("{OrderNo}", order.OrderNumber);
SendEmail(customer.Email, emailBody.ToString());
StringBuilder inputBuffer = new StringBuilder();
while (streamReader.Peek() >= 0)
{
inputBuffer.Append((char)streamReader.Read());
}
ProcessInput(inputBuffer.ToString());
StringBuilder jsonBuilder = new StringBuilder("[");
for (int i = 0; i < list.Count; i++)
{
jsonBuilder.Append(JsonConvert.SerializeObject(list[i]));
if (i < list.Count - 1)
jsonBuilder.Append(",");
}
jsonBuilder.Append("]");
string jsonArray = jsonBuilder.ToString();
```csharp
StringBuilder htmlPage = new StringBuilder("<html><body>");
foreach (var article in articles)
{
htmlPage.AppendFormat("<h2>{0}</h2><p>{1}</p>", article.Title, article.Content);
}
htmlPage.Append("</body></html>");
return htmlPage.ToString();
```
StringBuilder pathBuilder = new StringBuilder();
pathBuilder.Append(basePath);
foreach (string directory in directories)
{
pathBuilder.Append(Path.DirectorySeparatorChar);
pathBuilder.Append(directory);
}
string fullPath = pathBuilder.ToString();
```csharp
string[] parts = longString.Split(';');
StringBuilder rebuiltString = new StringBuilder();
for (int i = 0; i < parts.Length; i++)
{
rebuiltString.Append(parts[i].Trim());
if (i < parts.Length - 1)
rebuiltString.Append("; ");
}
string processedString = rebuiltString.ToString();
```
```csharp
StringBuilder tableBuilder = new StringBuilder();
foreach (var row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
tableBuilder.Append(row[i].ToString().PadRight(20));
if (i < dataTable.Columns.Count - 1)
tableBuilder.Append("|");
}
tableBuilder.AppendLine();
}
string formattedTable = tableBuilder.ToString();
```
```csharp
List<int> ids = GetIds();
StringBuilder inClause = new StringBuilder("IN (");
for (int i = 0; i < ids.Count; i++)
{
inClause.Append(ids[i]);
if (i < ids.Count - 1)
inClause.Append(",");
}
inClause.Append(")");
ExecuteSql($"SELECT * FROM Users WHERE Id {inClause.ToString()}");
```
```csharp
StringBuilder passwordHashBuilder = new StringBuilder();
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
foreach (byte b in hashBytes)
{
passwordHashBuilder.Append(b.ToString("x2"));
}
}
string passwordHash = passwordHashBuilder.ToString();
```
以上这些例子再次强调了在需要频繁修改和拼接字符串的场景下,StringBuilder相比于string能够显著提升性能。
python学习汇总连接:
50个开发必备的Python经典脚本(1-10)
50个开发必备的Python经典脚本(41-50)
————————————————
?最后我们放松一下眼睛