英文:
Using String.Join in String Builder C#
问题
以下是您要翻译的代码部分:
我正在尝试从GUID列表(约10000个)创建一个CSV字符串。我的代码片段如下。
private string GetAppInformationForCache()
{
StringBuilder appInfo = new();
var expiresString = $"Expires:{ExpirationDateTime:u};";
appInfo.Append("1:" + string.Join(",", DefaultCatalogAppIds) + ";");
appInfo.Append("L:" + string.Join(",", PrivateCatalogAppIds) + ";");
appInfo.Append("3:" + string.Join(",", GlobalCatalogAppIds) + ";");
appInfo.Append(expiresString);
return appInfo.ToString();
}
请注意,代码已保持原样,只进行了翻译。
英文:
I am trying to create a csv string from a list of GUIDs (around 10000) of them. My snippet is below.
private string GetAppInformationForCache()
{
StringBuilder appInfo = new ();
var expiresString = $"Expires:{ExpirationDateTime:u};";
appInfo.Append("1:" + string.Join(",", DefaultCatalogAppIds) + ";");
appInfo.Append("L:" + string.Join(",", PrivateCatalogAppIds) + ";");
appInfo.Append("3:" + string.Join(",", GlobalCatalogAppIds) + ";");
appInfo.Append(expiresString);
return appInfo.ToString();
}
This is in a high traffic API around 30K RPS. I am sure string.Join has some memory allocation concerns in such a high volume. I was asked to change this to a more performant implementation. I could not find a better way to do this except looping throught the guids and appending to resultant string builder.
Is there a more performant way to handle this?
答案1
得分: 3
你可以使用 AppendJoin
:
appInfo.Append("1:");
appInfo.AppendJoin(",", DefaultCatalogAppIds);
appInfo.Append(";");
以此类推。
英文:
You can use AppendJoin
:
appInfo.Append("1:");
appInfo.AppendJoin(",", DefaultCatalogAppIds);
appInfo.Append(";");
And so on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论