[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- 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)
> end
>
> 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?
#include <stddef.h>
#include <ctype.h>
#include <lua.h>
int trim(lua_State *L)
{
const char *front;
const char *end;
size_t size;
front = lua_tolstring(L,1,&size);
end = &front[size - 1];
lua_pop(L,1);
for ( ; size && isspace(*front) ; size-- , front++)
;
for ( ; size && isspace(*end) ; size-- , end--)
;
lua_pushlstring(L,front,(size_t)(end - front) + 1);
return 1;
}
int luaopen_trim(lua_State *L)
{
lua_register(L,"trim",trim);
return 0;
}
-spc (Compile into shared object, load using "require" ... )