1

I have created a function to 'filter' a string by removing various characters using the .Replace method, I am also removing anything at the end of the string that starts with '(' using the Substring method.

This all works fine, however I am wondering if there is a optimised better way of doing this as efficiency is important for me.

public static string filterHorseName(string horseName)
{
    horseName = horseName
      .Replace(" ", "")
      .Replace("`", "")
      .Replace("-", "")
      .Replace("'", "")
      .Replace("´", "")
      .Replace("’", "")
      .ToLower();

    int index = horseName.IndexOf("(");

    if (index > 0)
    {
        horseName = horseName.Substring(0, index);
    }

    return horseName;
}

Thank you.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Zack Antony Bucci
  • 571
  • 1
  • 12
  • 29
  • 1
    When you ask these types of questions its optimal to put in your inputs and intended outputs – TheGeneral May 13 '19 at 08:23
  • Efficiency is important for everyone. Did you benchmark this code? Is it proven to be a bottleneck? Don't just rename your horses, [race them](https://ericlippert.com/2012/12/17/performance-rant/). Anyway, you're creating a lot of garbage strings here. Each `Replace()` and `Substring()` returns a new string, leaving the old one eligible for garbage collection. – CodeCaster May 13 '19 at 08:24
  • Here is a lot of different way to do this. https://stackoverflow.com/questions/7265315/replace-multiple-characters-in-a-c-sharp-string. a simple https://github.com/dotnet/BenchmarkDotNet to race them? – xdtTransform May 13 '19 at 08:24
  • And as the replacment char is Nothing. wou can simply filter them with a Where clause. – xdtTransform May 13 '19 at 08:28
  • Consider using a StringBuilder to create the string. Strings are immutable objects, each time you do a Replace() you are creating a new instance. – muszeo May 13 '19 at 08:29

1 Answers1

4

I suggest building the final string with a help of StringBuilder:

    private static HashSet<char> charsToRemove = new HashSet<char>() {
      ' ', '`', '-', '\'', '´', '’'
    };

    public static string filterHorseName(string horseName) {
      if (string.IsNullOrEmpty(horseName)) 
        return horseName;

      StringBuilder sb = new StringBuilder(horseName.Length);  

      foreach (char c in horseName) {
        if (charsToRemove.Contains(c)) 
          continue;
        else if (c == '(') 
          break;

        sb.Append(char.ToLower(c));
      }

      return sb.ToString(); 
    } 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215