在C#中使用String.Join和StringBuilder。

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月8日 11:26:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定