lua-users home
lua-l archive

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


In some recents projects I have implemented an interpolated version of
assert, in which it justs comstructs the error message if the
expression evaluates to false. Example:

mob = getmob()
assert( mob:isalive(), "the mob {mob.name} must be alive" )

There is some black debug magic to get it working properly (handling
locals, globals, function environments etc) and also the problem that
it polutes the stack trace, but  I think it pays off in the end,
specially because the only overhead you have is only activated when
you need it, i.e. When the assertion fails.

On 5/20/10, Marc OMorain <marc.omorain@kore.net> wrote:
> 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
>>
>>
>

-- 
Sent from my mobile device