[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: the most optimal string "trim" implementation
- From: David Manura <dm.lua@...>
- Date: Sat, 26 Dec 2009 14:56:13 -0500
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)')
end