etls icon indicating copy to clipboard operation
etls copied to clipboard

optimisation when you play with atoms

Open silviucpp opened this issue 8 years ago • 0 comments

Hello,

Looking through the code I see when you play with atoms (at least for bool true and false) you are creating all the time them or extract the string in order to compare.

What you can do instead is:

You can declare a global struct with all atoms:

struct atoms
{
    ERL_NIF_TERM atomTrue;
    ERL_NIF_TERM atomFalse;
    //whatever else ...
};

In on_nif_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) you can initialize them:

ATOMS.atomTrue = make(env, str_atom("true"));
ATOMS.atomFalse = make(env, str_atom("false"));

I will also changed the following functions like


inline TERM make(ErlNifEnv *env, const str_atom &var)
{
    if(enif_make_existing_atom(env, var.c_str(), &ret, ERL_NIF_LATIN1))
        return TERM(ret);

    return TERM(enif_make_atom(env, var.c_str()));
}

// bool
inline int get(ErlNifEnv *env, ERL_NIF_TERM term, bool &var)
{
      if(enif_is_identical(term, ATOMS.atomTrue)
      {
           var = true;
           return 1;
      }

      if(enif_is_identical(term, ATOMS.atomFalse)
      {
            var = false;
           return 1;
      }

     return 0; // some other atom, return error
}
inline TERM make(ErlNifEnv *env, const bool var)
{
     return TERM(var ? ATOMS.atomTrue: ATOMS.atomFalse);
}

Kind regards, Silviu

silviucpp avatar Oct 29 '16 18:10 silviucpp