When to use Regex vs Built in String Methods?

后端 未结 6 667
庸人自扰
庸人自扰 2021-01-12 07:03

I\'ve noticed a lot of little debates about when to use regex and when to use a built in string function like String.Replace() (.NET).

It seems a lot of people recom

6条回答
  •  迷失自我
    2021-01-12 07:23

    Built-in string replace method is faster than the regex when you want to replace substrings. Here are the benchmark numbers in Golang, I have tried to replace 3 type substrings.

    Benchmark Replace 2 --- 236 ns/op

    Benchmark Replace 5 --- 249 ns/op

    Benchmark Replace 10 --- 871 ns/op

    Benchmark Regexp 2 --- 3750 ns/op

    Benchmark Regexp 5 --- 4457 ns/op

    Benchmark Regexp 10 --- 6020 ns/op

    As you can see Replace is far better than Regexp if you are replacing known substrings. But if you have to match unknown strings or patterns then regexp might be better.

提交回复
热议问题