> I know that Dart had a lot of problems with RegExp performance. As far as I know, it has been solved through a refactor in the RegExp engine, although I couldn't find any detailed information on this.
Not sure what this refers to, unless it's from before Dart switched from PCRE to the Irregexp engine. That was eons ago.
It's hard to say what creating an RegExp costs, because it depends on the regexp pattern. And how the implementation optimizes, which is always going to be speculative,
and will likely differ between platforms (native vs. web).
It's never free. Calling the `RegExp` constructor includes parsing the pattern (unless runtime internals cache between creations using the same pattern and flags, and who knows if it does),
and parsing is one of the more expensive tasks that a program can do. Parsing is generally expensive at the CPU level because it's usually full of unpredictable branches.
It needs to happen when calling the `RegExp` constructor, because that's when it must throw if the input is not valid.
But RegExp patterns are usually short, so again it's hard to say something definite.
The main compilation cost may be paid on first call (and maybe a later call too), since the implementation may compile separately for one-byte and two-byte string inputs,
so it needs to see the first input before knowing what kind of input to compile for.
The backend might share compilation artifacts between RegExp instances with the same pattern. Or it might not.
But it's not free to create the object, it always performs a memory allocation, and it needs to check the pattern syntax.
I'd personally always create a variable caching a regexp that I expect to reuse repeatedly.
But I'd cache any other cacheable object allocations that I expect to repeat as well (if I can't use a const object creation inline, and RegExps cannot be const).
This is performance. If the code is not on a critical path, maybe performance doesn't matter.
And if it is on a critical path, you should have measurements showing where the pain points are.
But I personally prefer to avoid creating RegExps repeatedly too, because it's unnecessary overhead, and it has unpredictable performance, because it
depends so much on which optimizations apply, and I prefer to not having to guess about those.
But that's just, like, my opinion man.
/L