Ben Mills
Ben Mills

Reputation: 28624

Is it bad to use regex based route constraints?

I have the following route that will be hit extensively on my ASP.NET MVC website:

    routes.MapRoute(
        null,
        "products/{ProductID}/{SeoName}",
        new { controller = "Product", action = "ProductDetails", SeoName = UrlParameter.Optional }
    );

I want to make sure that the ProductID is a valid integer. I know I can do this with a regular expression based route constraint or with a custom route constraint that does something like an int.TryParse().

It would seem to me that regular expressions are pretty expensive operations and I don't want to run one for every request that hits my website, but I can't seem to find any information that says I should be careful using regex based route constraints.

So my question is, should I use a regex based route constraint or a custom route constraint to verify that a parameter is an integer?

Upvotes: 0

Views: 3108

Answers (2)

Giscard Biamby
Giscard Biamby

Reputation: 4619

Sam Saffron blogged about the optimizations he helped make on StackExchange sites. One of the things he did was get rid of as many regex constraints as possible. It's fairly simple to replace regex constraints with a custom IRouteConstraint implementation if you just need to make sure something is an integer. Sam's post has an example of the code he used for this very thing. Check it out here: http://samsaffron.com/archive/2011/10/13/optimising-asp-net-mvc3-routing

That said, it is unlikely to cause performance problems for you unless your site is getting a lot of traffic, and/or you have a ton of routes. I wouldn't worry about doing this up front until after I got a site working and launched.

Upvotes: 5

kastermester
kastermester

Reputation: 3064

While I am not entirely certain how the .Net regex engine performs with regards to simple regexes like this - as known from the CS courses, a Finite Automaton can recognise regular languages in linear time. To determine if a string is a number you will need to visit every character of the string either way, so as such, theoretically it should not matter much.

However as stated in one of the other answers it might be likely that something like Int32.TryParse is more optimized for doing this (in some odd way) and as such could be marginally faster.

But a compiled regular expression really should do any average user just fine, unless the implementation of the regular expression engine is absolutely horrible. Of course this is assuming your regular expression is actually recognising a regular language (ie look aheads and look behinds are a nono, and your regular expression cannot cause any kind of backtracking) - which testing for an integer is.

However as stated, please note I have done no testing on any of this, so I have no real data to back any of these claims up with.

Upvotes: 0

Related Questions