lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 26-12-2009 20:56, David Manura wrote:
On Fri, Dec 25, 2009 at 12:25 AM, David Manura wrote:
I contend [1] that the most optimal way to implement a string "trim"
function is basically this:
  function trim(s) return s:match'^%s*(.*%S)%s*$' or '' end
On Sat, Dec 26, 2009 at 1:03 AM, David Manura wrote:
On Fri, Dec 25, 2009 at 6:22 AM, Shmuel Zeigerman wrote:
  function trim(s) return s:match'^%s*(.*%S)' or '' end
Yes, that is even better.

I'll have to retract this conclusion.  The implementation performs
very well except in the case of a long string with only whitespace, in
which case it performs very poorly.  In the latter condition the
pattern finds no match, and the juxtaposition of "%s*" with ".*"
causes substantial backtracking (see recent "Pattern matching: good
practices ?" thread).  So, I fall back to the following as the most
optimal known implementation:

   local match = string.match
   function trim(s)
     return match(s,'^%s*$') and '' or match(s,'^%s*(.*%S)')

how about

return find(s,'^%s*$') and '' or match(s,'^%s*(.*%S)')

                                          Hans Hagen | PRAGMA ADE
              Ridderstraat 27 | 8061 GH Hasselt | The Netherlands
     tel: 038 477 53 69 | fax: 038 477 53 74 |