1

Lets say we have the following function, which version is better?

void doMagic()
{
   var sb = new StringBuilder();
   foreach(var e in this.Elements)
   {
      // version 1
      sb.Append(e.Name).Append("|").Append(e.Descripion);
      // version 2
      sb.Append($"{e.Name}|{e.Descripion}");
   }
}

Does it even make a compiler difference ? From readability perspective I like version 2 more

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
  • 3
    Aim for readability first. Only when you identify a block of code as bottleneck, sacrifice (some) readability for performance improvements. – knittl Nov 28 '22 at 19:24
  • 1
    I don't see string concatenation – Thomas Weller Nov 28 '22 at 19:27
  • 1
    https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEB0AVApgDwC4G5YQBmZMRAYUQG9ZF7lSQAWRAWQAoBKGuhhgG4BDAE6IAzgCNEAXkQA7TAHdEAZVwiAlvIDmAIQCumgDYATTCO6EY/BgDMA9iMxCAxgAsOwsZkTaFygDaALo0AERCkmEAvlx8trQ2tvwA9CmIAhbimg7yiNBJyfRSqACCAA7lmPKmHJiB8MFcZZXVtWHAYc0VVTV1gRBN1kUMaRlZOXlg8UUlPW0cACRh1PWN0cCrA8HRXcPJ0TOHMNFAA= – 41686d6564 stands w. Palestine Nov 28 '22 at 19:27
  • @ThomasWeller $"{e.Name}|{e.Descripion}" == e.Name + "|" + e.Description – user2292496 Nov 28 '22 at 19:28
  • No, that's not the equivalent. Learn how a StringBuilder works, then come back. – Thomas Weller Nov 28 '22 at 19:29
  • 1
    I'd go even further and cut out the `StringBuilder` too, in favor of a `String.Join` call on `this.Elements.Select()`. One day I might find this happens in a place where this is a bottleneck -- but it hasn't happened yet. – Jeroen Mostert Nov 28 '22 at 19:29
  • You know you CAN do it. Yes, there is a slight perf difference. You most likely won't notice it, though, so go with readability. I linked a similar question that I think answers your underlying question. – Rufus L Nov 28 '22 at 19:38
  • @RufusL Thank you very much. With the help of your linked answer I got an idea. Why not writing an stringbuilder extension taking a params string[]; having something like sb.Appendx(e.Name, "|", "e.Descripion"); or sb.AppendLinex(e.Name,"|",e.Description); – user2292496 Nov 28 '22 at 19:52
  • If that's more readable or efficient for you, go for it. – Rufus L Nov 28 '22 at 20:03
  • `string result = string.Concat(Elements.Select(e => $"{e.Name}|{e.Descripion}"))` is also equivalent. But if you want each item on it's own line (i.e. `AppendLine` instead of `Append` for the `StringBuilder`), you can do: `string.Join(Environment.NewLine, Elements.Select(e => $"{e.Name}|{e.Descripion}"))` – Rufus L Nov 28 '22 at 20:11
  • 2
    @RufusL Closing a C# question as a duplicate to a Java question doesn't make much sense. – Mark Rotteveel Nov 29 '22 at 09:25
  • @MarkRotteveel somehow I missed that, thanks for reopening! – Rufus L Nov 29 '22 at 18:13

0 Answers0