Does calling stoi with a (NULL-terminated) char* necessarily construct a temporary string and hence lead to a performance penalty?
Does calling stoi with a (NULL-terminated) char* necessarily construct a temporary string and hence lead to a performance penalty?
Conceptually yes it would. There is no overload of std::stoi that takes a const char* as an argument, so an anonymous temporary std::string is created.
That indeed is a string copy.
You could check the assembly code to see if that's what your compiler does. It might optimise to
std::strtol
or
std::strtoll
If your compiler doesn't make that optimisation, and it turns out (by profiling) that the string copy is a bottleneck, then hand-roll the alternative as above.
According to cppreference, these are the following overloads for stoi:
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
int stoi( const std::wstring& str, std::size_t* pos = 0, int base = 10 );
So since there is no overload that takes a const char *, unless the compiler is doing some optimization, yes, if you enter a const char *, it will create a temporary std::string object. Of course, the compiler can do optimizations. If you look at the assembly of this small program compiled with -O3, you'll see a call strtol in main there. That means the compiler has indeed optimized the stoi out completely.