Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL terminated string and its length

Tags:

c++

gcc

cstring

I have a legacy code that receives some proprietary, parses it and creates a bunch of static char arrays (embedded in class representing the message), to represent NULL strings. Afterwards pointers to the string are passed all around and finally serialized to some buffer.

Profiling shows that str*() methods take a lot of time.

Therefore I would like to use memcpy() whether it's possible. To achive it I need a way to associate length with pointer to NULL terminating string. I though about:

  • Using std::string looks less efficient, since it requires memory allocation and thread synchronization.

  • I can use std::pair<pointer to string, length>. But in this case I need to maintain length "manually".

What do you think?

like image 375
dimba Avatar asked Jan 21 '23 23:01

dimba


2 Answers

use std::string

like image 136
swegi Avatar answered Jan 31 '23 04:01

swegi


Profiling shows that str*() methods take a lot of time

Sure they do ... operating on any array takes a lot of time.

Therefore I would like to use memcpy() whether it's possible. To achive it I need a way to associate length with pointer to NULL terminating string. I though about:

memcpy is not really any slower than strcpy. In fact if you perform a strlen to identify how much you are going to memcpy then strcpy is almost certainly faster.

Using std::string looks less efficient, since it requires memory allocation and thread synchronization

It may look less efficient but there are a lot of better minds than yours or mine that have worked on it

I can use std::pair. But in this case I need to maintain length "manually".

thats one way to save yourself time on the length calculation. Obviously you need to maintain the length manually. This is how windows BSTRs work, effectively (though the length is stored immediately prior, in memory, to the actual string data). std::string. for example, already does this ...

What do you think?

I think your question is asked terribly. There is no real question asked which makes answering next to impossible. I advise you actually ask specific questions in the future.

like image 27
Goz Avatar answered Jan 31 '23 05:01

Goz