[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lua in high performance apps
- From: "Joshua Jensen" <jjensen@...>
- Date: Mon, 16 Apr 2001 23:11:57 -0600
From: "Steve Dekorte" <steve@dekorte.com>
Sent: Monday, April 16, 2001 10:13 PM
> On Monday, April 16, 2001, at 08:15 PM, Joshua Jensen wrote:
>
> > 2) for loops are quite a bit faster than while loops, since they have
> > specialized virtual machine instructions.
>
> By "for loop" do you mean lua 4.0's for loop or foreach() and foreachi()?
> Anyone now how foreach and foreachi compare in speed to while or for?
I mean the built-in for loop:
for i = 1, 1000, 1 do
-- Stuff
end
As far as foreach and foreachi, a quick check of the source code reveals:
static int luaB_foreachi (lua_State *L) {
int n, i;
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);
n = lua_getn(L, 1);
for (i=1; i<=n; i++) {
lua_pushvalue(L, 2); /* function */
lua_pushnumber(L, i); /* 1st argument */
lua_rawgeti(L, 1, i); /* 2nd argument */
lua_rawcall(L, 2, 1);
if (!lua_isnil(L, -1))
return 1;
lua_pop(L, 1); /* remove nil result */
}
return 0;
}
static int luaB_foreach (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_pushnil(L); /* first index */
for (;;) {
if (lua_next(L, 1) == 0)
return 0;
lua_pushvalue(L, 2); /* function */
lua_pushvalue(L, -3); /* key */
lua_pushvalue(L, -3); /* value */
lua_rawcall(L, 2, 1);
if (!lua_isnil(L, -1))
return 1;
lua_pop(L, 2); /* remove value and result */
}
}
Based on what I see above, I'd wager that a straight for loop in Lua is a
lot faster than foreachi, if only for the reason that foreachi calls
lua_rawcall. A 'for key, value in table' in Lua is probably also faster
than foreach for the same reason. But I haven't benchmarked either to be
sure.
Thanks,
Josh
----------
Author, Workspace Whiz! - A Visual Studio Add-in
http://workspacewhiz.com/