Avatar of the person chatting

2 / 2This function is pretty slow, can you make it run faster: public string GenerateCsv(User[] users){ var csv = ""; foreach(var user in users){ csv += user.Name + "," + user.Age + "," + user.Email + "\r\n"; } return csv; }

Yes, this function can be optimized for faster performance. One approach could be to use a StringBuilder instead of concatenating strings in a loop. String concatenation can become slow with a large number of iterations. The StringBuilder object allows us to build a string dynamically and is optimized for multiple appends.

Here's the optimized version:

public string GenerateCsv(User[] users){ var csv = new StringBuilder();

foreach(var user in users){ csv.Append(user.Name + "," + user.Age + "," + user.Email + "\r\n"); } return csv.ToString();