lua-users home
lua-l archive

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


There are very often hidden penalties associated with assert.

Consider the following code, where object is a userdata (userdatum?)
(This would be a very common code pattern in my field).

assert(object:isValid(), "object " .. object:getName() " .. " is not valid")

object:getName() calls the following function:

static int object_getname(lua_State* L)
{
  lua_pushstring(L, "the object's name");
  return 1;
}

As a C programmer, I would expect that line of code to produce no code
in my release build.

In Lua, the call to assert() is probably the most expensive line of
code in my function however. There are always 3 function calls, to
assert(), isValid() and getName(), 2 of which will go through the
__call infrastructure, since object is a userdata. 2 new strings are
(very likely) created, these are (very likely) immediately going to
become garbage. (One string in object_getname(), one in the
concatenation operation).

Much of the overhead can be avoided by using an if statement rather
than an assert:

if not object:isValid() then error("object " .. object:getName() " ..
" is not valid") end

This at least defers the majority of the work until the condition
fails, which is (by definition) unlikely.

Thanks,

Marc


On 20 May 2010 09:17, Nikolai Kondrashov <spbnick@gmail.com> wrote:
> On 05/19/2010 11:44 PM, HyperHacker wrote:
>>
>> Some would call this premature optimization. Don't bother to speed it
>> up until you know it's slow.
>
> Thanks, yeah, I agree. I'm not doing anything until it proves to slow things
> down :)
>
> Sincerely,
> Nick
>
>