What is faster Regex or a Loop in C#? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is faster Regex or a Loop in C#?

Lets say you want to find a character or another string inside a particular string, which one will do the work faster and more efficiently Regex or a loop?

20th Jul 2021, 3:00 AM
Mufungo Geeks
Mufungo Geeks - avatar
3 Answers
+ 4
Mufungo Geeks No contest... generally speaking you don't use RegEx where performance is critical. It's a great tool used for convenience and rarely have I had to care about the perf difference. But... in scenarios where performance matters, stick with alternative approaches to RegEx.
20th Jul 2021, 6:39 AM
David Carroll
David Carroll - avatar
+ 3
I'm not into comparing RegEx with specific string related methods, just thought RegEx was meant as a universal tool that doesn't concern much about per language syntax. I think RegEx was invented with compatibility in mind, like XML or JSON for data exchange. RegEx, XML and JSON has their own standard protocol such that they work disregarding which language involved for development. If we understand RegEx, then we can do the same thing in various language without having to worry about syntax differences, though inevitably, there are some. Just what I had in mind, cmiiw 👌
20th Jul 2021, 4:26 AM
Ipang
+ 2
Mufungo Geeks Of course, loops are faster as they can do the job in a lesser amount of machine instructions as compared to regex. Regex needs to care about all the patterns, so it's not so efficient.
20th Jul 2021, 5:38 AM
Calvin Thomas
Calvin Thomas - avatar