Skip to content

Commit

Permalink
perf: don't recompile escapeRegExp for every query (#8956)
Browse files Browse the repository at this point in the history
Context: the query builder is pretty CPU intensive, and can be slow -
e.g. #3857

One of the things which makes this slow is `escapeRegExp` in the query
builder: we freshly construct the same RegExp once per
`replacePropertyName` invocation (many times per overall query!) and
since the RegExp itself is constant -- we can lift it out and construct
it once.

Over-all this saves about 8% on our query build times as measured by
 #8955.
  • Loading branch information
draaglom committed May 20, 2022
1 parent 22570f5 commit 189592c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
7 changes: 2 additions & 5 deletions src/query-builder/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { EntityPropertyNotFoundError } from "../error/EntityPropertyNotFoundErro
import { ReturningType } from "../driver/Driver"
import { OracleDriver } from "../driver/oracle/OracleDriver"
import { InstanceChecker } from "../util/InstanceChecker"
import { escapeRegExp } from "../util/escapeRegExp"

// todo: completely cover query builder with tests
// todo: entityOrProperty can be target name. implement proper behaviour if it is.
Expand Down Expand Up @@ -701,12 +702,8 @@ export abstract class QueryBuilder<Entity> {
/**
* Replaces all entity's propertyName to name in the given statement.
*/
protected replacePropertyNames(statement: string) {
// Escape special characters in regular expressions
// Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
const escapeRegExp = (s: String) =>
s.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&")

protected replacePropertyNames(statement: string) {
for (const alias of this.expressionMap.aliases) {
if (!alias.hasMetadata) continue
const replaceAliasNamePrefix = this.expressionMap
Expand Down
4 changes: 4 additions & 0 deletions src/util/escapeRegExp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Escape special characters in regular expressions
// Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
const ESCAPE_REGEXP = /[.*+\-?^${}()|[\]\\]/g
export const escapeRegExp = (s: String) => s.replace(ESCAPE_REGEXP, "\\$&")

0 comments on commit 189592c

Please sign in to comment.