Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace much slower than conditional statement using String.Contains

I have a list of 400 strings that all end in "_GONOGO" or "_ALLOC". When the application starts up, I need to strip off the "_GONOGO" or "_ALLOC" from every one of these strings.

I tried this: 'string blah = Regex.Replace(string, "(_GONOGO|_ALLOC)", ""));'

but it is MUCH slower than a simple conditional statement like this:

if (string.Contains("_GONOGO"))
          // use Substring
else if (string.Contains("_ALLOC"))
          // use Substring w/different index

I'm new to regular expressions, so I'm hoping that someone has a better solution or I am doing something horribly wrong. It's not a big deal, but it would be nice to turn this 4 line conditional into one simple regex line.

like image 641
alexD Avatar asked Nov 26 '25 23:11

alexD


2 Answers

While it isn't RegEx, you could do

string blah = string.Replace("_GONOGO", "").Replace("_ALLOC", "");

RegEx is great for complex expressions, but the overhead can sometimes be overkill for very simple operations like this.

like image 63
Adam Robinson Avatar answered Nov 28 '25 11:11

Adam Robinson


Regex replacements may work faster if you compile the regex first. As in:

Regex exp = new Regex(
    @"(_GONOGO|_ALLOC)",
    RegexOptions.Compiled);

exp.Replace(string, String.Empty);
like image 44
David Andres Avatar answered Nov 28 '25 13:11

David Andres