Greedy and lazy quantifiers are equally expensive when used correctly. However, lazy quantifiers have gained a bad reputation for being slow because they can be applied and are often used to compensate for inaccuracies in the pattern.
Consider a simple example: <.*?>
Vs. <.*>
.
When both expressions apply to the same input
<abcdefghijklmnopqrstuvwxyz0123456789>
they correspond to the exact text. The only difference is how they get into the match: the "lazy" expression puts longer and longer lines, reaching the match after 40 steps ( demo 1 ). The greedy expression, on the other hand, goes all the way and returns once to come to the match in only 5 steps ( demo 2 ).
Please note that the situation can be reversed if after >
add more characters:
<abcdefghijklmnopqrstuvwxyz0123456789>abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789
Now the greedy expression becomes โslowโ, taking 149 steps ( demo 3 ), while the lazy expression continues to take the same 40 steps as before ( demo 4 ).
source share