Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
You are correct that the pattern .*?foo can be written as (?:[^f]+|f(?!oo))*foo, or the variant you showed. You are correct in assuming that this general principle can be used for practically any regex.

However, you should "unroll the loop" of that regex. Look at these results:

use Benchmark 'cmpthese'; my $str = "this is the best end"; cmpthese(-5, { extra => sub { $str =~ /(?:[^e]+|e(?!nd))*end/ }, plain => sub { $str =~ /.*?end/ }, }); __END__ extra: 12019.37/s (n=60818) plain: 49615.59/s (n=283305) Rate extra plain extra 12019/s -- -76% plain 49616/s 313% --
If we unroll the loop, we get better results.
use Benchmark 'cmpthese'; my $str = "this is the best end"; cmpthese(-5, { extra => sub { $str =~ /(?:[^e]+|e(?!nd))*end/ }, plain => sub { $str =~ /.*?end/ }, uroll => sub { $str =~ /[^e]*(?:e(?!nd)[^e]*)*end/ }, }); __END__ extra: 11711.62/s (n=61486) plain: 49329.33/s (n=250593) uroll: 17985.61/s (n=94964) Rate extra uroll plain extra 11712/s -- -35% -76% uroll 17986/s 54% -- -64% plain 49329/s 321% 174% --
But the point is, the internal optimization uses less regex op-codes, and so it is faster -- it has the engine do the work itself, it doesn't make the regex do the work.

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;


In reply to Re: Avoiding regex backtracking by japhy
in thread Avoiding regex backtracking by Aristotle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-25 07:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found