[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: the most optimal string "trim" implementation
- From: Sean Conner <sean@...>
- Date: Mon, 28 Dec 2009 22:39:46 -0500
It was thus said that the Great David Manura once stated:
> On Sat, Dec 26, 2009 at 6:31 PM, Shmuel Zeigerman wrote:
> > [this] slightly outperformed your variant, except for the all-space strings,
> > where it performed worse (which I don't understand why).
> > function trim(s)
> > local from = s:find("%S")
> > return from and s:match(".*%S", from) or ""
> > end
> This variant of yours performs much better in the worst case and has
> about the same performance overall as my last one:
> function trim(s)
> local from = s:match"^%s*()"
> return from > #s and "" or s:match(".*%S", from)
> For some reason, s:find"^%s*$" is about twice as fast as s:find"%S"
> given s = (" "):rep(100).
I guess the following would be considered "cheating" then?
int trim(lua_State *L)
const char *front;
const char *end;
front = lua_tolstring(L,1,&size);
end = &front[size - 1];
for ( ; size && isspace(*front) ; size-- , front++)
for ( ; size && isspace(*end) ; size-- , end--)
lua_pushlstring(L,front,(size_t)(end - front) + 1);
int luaopen_trim(lua_State *L)
-spc (Compile into shared object, load using "require" ... )