Skip to content

Commit

Permalink
perf: don't recompile escapeRegExp for every query (typeorm#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. typeorm#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
 typeorm#8955.
  • Loading branch information
draaglom authored and frangz committed Nov 14, 2022
1 parent bda2c2c commit 1631cfb
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
5 changes: 1 addition & 4 deletions src/query-builder/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {EntitySchema} from "../";
import {FindOperator} from "../find-options/FindOperator";
import {In} from "../find-options/operator/In";
import {EntityColumnNotFound} from "../error/EntityColumnNotFound";
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 @@ -576,10 +577,6 @@ 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, "\\$&");

for (const alias of this.expressionMap.aliases) {
if (!alias.hasMetadata) continue;
const replaceAliasNamePrefix = this.expressionMap.aliasNamePrefixingEnabled ? `${alias.name}.` : "";
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 1631cfb

Please sign in to comment.