From d30b780900d9fc3706614d1c160a8cff9c38819c Mon Sep 17 00:00:00 2001 From: Eric Proulx Date: Mon, 16 Dec 2019 14:28:41 +0100 Subject: [PATCH] Regex string allocation (#1943) Use Regexp instead of // for regex in router.rb for a more efficient string allocation. --- CHANGELOG.md | 1 + lib/grape/router.rb | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7721c05772..d9f353a234 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * Your contribution here. * [#1944](https://github.com/ruby-grape/grape/pull/1944): Reduced attribute_translator string allocations - [@ericproulx](https://github.com/ericproulx). +* [#1943](https://github.com/ruby-grape/grape/pull/1943): Reduce number of regex string allocations - [@ericproulx](https://github.com/ericproulx). * [#1942](https://github.com/ruby-grape/grape/pull/1942): Optimized retained memory methods - [@ericproulx](https://github.com/ericproulx). * [#1941](https://github.com/ruby-grape/grape/pull/1941): Frozen string literal - [@ericproulx](https://github.com/ericproulx). * [#1940](https://github.com/ruby-grape/grape/pull/1940): Get rid of a needless step in HashWithIndifferentAccess - [@dnesteryuk](https://github.com/dnesteryuk). diff --git a/lib/grape/router.rb b/lib/grape/router.rb index 509c1a2730..b309088427 100644 --- a/lib/grape/router.rb +++ b/lib/grape/router.rb @@ -41,7 +41,7 @@ def compile! routes = map[method] @optimized_map[method] = routes.map.with_index do |route, index| route.index = index - route.regexp = /(?<_#{index}>#{route.pattern.to_regexp})/ + route.regexp = Regexp.new("(?<_#{index}>#{route.pattern.to_regexp})") end @optimized_map[method] = Regexp.union(@optimized_map[method]) end @@ -53,7 +53,7 @@ def append(route) end def associate_routes(pattern, **options) - regexp = /(?<_#{@neutral_map.length}>)#{pattern.to_regexp}/ + regexp = Regexp.new("(?<_#{@neutral_map.length}>)#{pattern.to_regexp}") @neutral_map << Any.new(pattern, regexp, @neutral_map.length, **options) end