A
A
Alexey2019-02-05 16:35:43
JavaScript
Alexey, 2019-02-05 16:35:43

Caching a regular expression from a function?

Can v8, well, or other engines in the node optimize a function call with a regular expression? In general, which of the options is preferable.
one.

function isValidPropNumber(propNumber) {
  return /^[1-9][0-9]{0,14}$/.test(propNumber);
};

2. Well, further in a larger function, it is used at some of the stages of verification
const REGEX = /^[1-9][0-9]{0,14}$/;
heavyFunction() {
//... много кода
if (isValidPropNumber(something) || REGEX.test(something)) { };
//... еще много кода
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kositsyn, 2019-02-05
@alex_keysi

The second one is preferable. I think that for v8 it is thousandths of a second to create this object again. And it will not be cached, because the object was created in the context of the function and after the function is executed, the reference to it will be lost, because the scope of the function is deleted after its execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question