Search code examples
optimizationluaffiluajit

LuaJIT FFI string comparison


I'm binding a third-party C API that uses string statuses a lot. E.g. (pseudocode):

ffi.cdef [[
  struct Reply { char * str; size_t len };
  Reply * doSomething();
  void freeReply(Reply * p);
]]

Most often str would be an "OK" string.

What is the fastest way to check that?

I would like to avoid string interning here:

local reply = ffi.gc(ffi.C.doSomething, ffi.C.freeReply)
assert(ffi.string(reply.str, reply.len) == "OK")

Solution

  • Not sure it is that much faster. What I would try is to call the strncmp from the standard C library.

    Something like this:

    ffi.cdef [[
      int strncmp ( const char * str1, const char * str2, size_t num );
    ]]
    
    local ok = ffi.new("char[3]", "ok")
    
    local reply = ffi.gc(ffi.C.doSomething, ffi.C.freeReply)
    assert(ffi.C.strncmp(ok, reply.str, reply.len) == 0)
    

    You may also try to first check that reply.len is 2 and then call memcmp instead of strncmp. It may be a little faster.