in reply to Inefficient regex

I assume that you're recursively decomposing the string from with myfunc(). If that's the case, then consider what's happening as you process a large string. Each time you match and substitute, you're building a new large string out of pieces of the old large string. When you do several substituions on a 500K string, you'll get a lot of memory shuffling.

An alternate approach is to break the input string into fragments, operate on the fragments, and then reassemble (i.e., join) an output string from fragments when you're finished.

My favorite tools for breaking a large string into pieces are the \G assertion, coupled with /c. Find both in perlre.