5
Comments
  • 1
    If I'm not mistaken, this is the slowest possible way to build strings in C#
  • 2
    Also ignore the SQL injection, that is not the point right now and only about 100 people are supposed to have access to the endpoints that can exploit it.
  • 2
    StringBuilder with interpolation, you mean? If it's in a loop it's probably not the slowest.
  • 3
    @lorentz Slowest?

    foreach (var c in new[] { " and ", columnExpression, " like ", valueExpression }.SelectMany(x => x)) filter.Append(c);
  • 0
    @lorentz @spongessuck It'll also likely get optimized away. I would be surprised if the CLR doesn't have transformation passes for repeated string concatenations like this
  • 1
    @12bitfloat That's the thing! It does. within roughly a function, C# will replace strings that are repeatedly concatenated with ropes. If the code only used string concatenation, this optimization would kick in and it would be faster than a stringbuilder because although it's not visible on the screenshot, this function basically just does a ton of string concatenation, which would translate into small allocations, most of them static size and therefore stack promotable.

    However, stringbuilders don't work with ropes, they work with a buffer, so I think this forces C# to first convert the rope into a CLR string primitive (copy everything together into a newly allocated space) and then copy it to the end of the stringbuilder.
  • 1
    I'm not fully confident that they didn't improve ropes in the mean time, when they were introduced they worked like this, and it wasn't a problem because the idea was to replace stringbuilder with a pattern that requires less forethought to be efficient.
Add Comment