开发者

is regex faster than if else?

开发者 https://www.devze.com 2023-03-26 15:37 出处:网络
I have a webserver program to process requests from browser, which is written in c++. There are lots of services, bbs/wiki/news, to name just a few. They have different url, for instance:

I have a webserver program to process requests from browser, which is written in c++. There are lots of services, bbs/wiki/news, to name just a few. They have different url, for instance:

  1. /bbs/viewtopic?tid=1

  2. /wiki/doc?did=1

  3. /news/artical?aid=1

now I do URI parse myself, then do if else. I'll take bbs as an example here, if string starts with /bbs/, bbs will take over then following process, then bbs will continue to check if it is viewtopic, if so, sever will sent topic content to client side...

I have a lot of if else to dispatch request to different service, meanwhile, each service has a lot if else to do different actions as well.

I don't know whether if else is a 开发者_Python百科smart choice, even thoug codes are easy to understand. Is regex is faster for such application?

Thanks for your participation:)


Generally, generic programming frameworks (which include using a regex) result in slower code that is faster to write. What a regex library will probably get you is a lot of time saved writing code at the price of an unimportant amount of CPU time. More often bottlenecks will be things like bandwidth, disk io and CPU usage by a database (if it's on the same machine).

If it's that important, I will say definitively that you can get faster code by avoiding a regex library, but you should benchmark your implementation, if for no other reason than being able to improve it. I haven't tested one in C++ to know how efficient they are, but testing the routines in a sample program would be little extra work.


If your if/else simply checks the string's prefix, then it would be faster. If it is something more complicated, requiring multiple passes over the string, then you should measure performance yourself.

Great engineering comes from creating predictable results at predictable costs. In fact, I like to say that if you’re not measuring you’re not engineering.

Rico Mariani

0

精彩评论

暂无评论...
验证码 换一张
取 消