Build Route Regex once to reduce allocations

Right now every `match?` performed against the routes defined result
in a new Regex compiled for the exact same `@path`.

Since `@path` of the Route does not change on every request, we
pre-build it to avoid repeated allocations.

When testing this in release mode (against 0.10.2 [d1e3f0b]):

Before: 32408.48 req/s
After:  34862.07 req/s
This commit is contained in:
Luis Lavena 2016-01-18 13:48:41 -03:00
parent 788c7241d4
commit df359d66c9

View file

@ -6,13 +6,14 @@ class Kemal::Route
getter method
def initialize(@method, @path, &@handler : Kemal::Context -> _)
@compiled_regex = pattern_to_regex(@path)
end
def match?(request)
check_for_method_override!(request)
return nil unless request.override_method == @method
return true if request.path.not_nil!.includes?(':') && request.path.not_nil! == @path
request.path.not_nil!.match(pattern_to_regex(@path)) do |url_params|
request.path.not_nil!.match(@compiled_regex) do |url_params|
request.url_params = url_params
return true
end