#35518: Avoid regex search for simple route patterns
-------------------------------------+-------------------------------------
Reporter: Jake | Owner: Jake Howard
Howard |
Type: | Status: assigned
Cleanup/optimization |
Component: Core | Version: 5.0
(URLs) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 1
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
The `RoutePattern` assumes all routes provided include some form of
converter, and so needs to change it into a regex for matching. However,
if no converters are included in the string, the additional overhead of
using a regex vs simpler string operations is unnecessary.
Replacing this with a simpler string comparison results in between a 50
and 75% reduction in match time, which stacks up quickly as an application
generally has numerous URLs. This can be done by modifying the
`RoutePattern` internally, with no external breakages.
**Before**
{{{#!python
In [2]: endpoint_pattern = RoutePattern("foo/", "name", is_endpoint=True)
In [3]: pattern = RoutePattern("foo/", "name", is_endpoint=False)
In [4]: %timeit pattern.match("foo/")
441 ns ± 2.68 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops
each)
In [5]: %timeit endpoint_pattern.match("foo/")
435 ns ± 0.974 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops
each)
}}}
**After**
{{{#!python
In [4]: %timeit pattern.match("foo/")
187 ns ± 1.84 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops
each)
In [5]: %timeit endpoint_pattern.match("foo/")
103 ns ± 0.192 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops
each)
}}}
Theoretically, these improvements get better based on the length of the
route pattern (although at this scale, not notably).
This optimisation could be done by adding a different kind of pattern (eg
`LiteralPattern`), but the added complexity to a project probably isn't
necessary, not to mention the migration effort to take advantage of this.
--
Ticket URL: <
https://code.djangoproject.com/ticket/35518>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.