lundi 28 novembre 2016

Efficient Memory Use Adding Buffer Output To Hash Table C++

This code fully works, but wonder if there is a more efficient way to write this code.

Some points:

  • RetrieveData is 3rd party API that takes 3 parameters - pointer to buffer containing the data, number of bytes to retrieve, actual number of bytes to retrieve
  • The buffer returned from retrieve data is non-null terminated unicode string
  • 99% of the time buffer is <256 bytes in size, but larger size is possible and needs to be handled
  • Reason adding data to map is later the "ID" must be retrieved based on string data

    std::map<std::wstring, unsigned int> map_columns;
    do 
    {
            unsigned int id;
            unsigned long pcbActual;
            char * data;
            {
                RetrieveID(&id);
                // RetrieveData ( <pointer to buffer for data>, <amount of bytes to retrieve>, <output actual bytes of data>)
                // find out how large buffer we need to retrieve data
                RetrieveData(NULL, 0, &pcbActual);
                data = new char[pcbActual + 2];
                // actually retrieve data
                RetrieveData(data, pcbActual, &pcbActual);
                // add null terminator to returned string
                data[pcbActual] = '\0';
                data[pcbActual + 1] = '\0';
                std::wstring str((wchar_t*)data);
                map_columns[str] = id;
            }
        } while (MoveNext());
    
    

Aucun commentaire:

Enregistrer un commentaire