Efficient way to convert int to string

I am creating a game in which I have a main loop. Within one cycle this cycle I need to convert the value intto stringabout 50-100 times. So far I have used this function:

std::string Util::intToString(int val)
{
   std::ostringstream s;
   s << val;
   return s.str();
}

But it does not seem efficient enough, as I was faced with the fall of FPS from ~ 120 (without using this function) to ~ 95 (when using).

Is there any other way to convert intto stringthat would be much more efficient than my function?

+5
source share
6 answers

This is a 1-72 range. I do not need to deal with negatives.

/ 73 string , . const, /:

// Initialize smallNumbers to strings "0", "1", "2", ...
static vector<string> smallNumbers;

const string& smallIntToString(unsigned int val) {
    return smallNumbers[val < smallNumbers.size() ? val : 0];
}
+8

std::to_string.

, , ? , . , std::to_string, , , ++ 11 .

+4

Yep β€” C, :

namespace boost {
template<>
inline std::string lexical_cast(const int& arg)
{
    char buffer[65]; // large enough for arg < 2^200
    ltoa( arg, buffer, 10 );
    return std::string( buffer ); // RVO will take place here
}
}//namespace boost

, . ltoa ( ), .

.

, :

template <typename T>
inline std::string fast_lexical_cast(const T& arg)
{
    return boost::lexical_cast<std::string>(arg);
}

template <>
inline std::string my_fast_lexical_cast(const int& arg)
{
    char buffer[65];

    if (!ltoa(arg, buffer, 10)) {
       boost::throw_exception(boost::bad_lexical_cast(
          typeid(std::string), typeid(int)
       ));
    }

    return std::string(buffer);
}

std::string myString = fast_lexical_cast<std::string>(42);

: SO- Kirill, , . - , .

+2

- :

 const int size = 12;
 char buf[size+1];
 buf[size] = 0;
 int index = size;
 bool neg = false
 if (val < 0) {    // Obviously don't need this if val is always positive.
    neg = true;
    val = -val;
 }

 do
 {
     buf[--index] = (val % 10) + '0';
     val /= 10;
 } while(val);
 if (neg)
 {
    buf[--index] = '-';
 }
 return std::string(&buf[index]);
+1

:

void append_uint_to_str(string & s, unsigned int i)
{
    if(i > 9)
        append_uint_to_str(s, i / 10);
    s += '0' + i % 10;
}

:

if(i < 0)
{
    s += '-';
    i = -i;
}

.

0

Your function should constantly create a stream of strings, which, as I heard, is expensive.

Why not use a static line stream for all your conversions?

0
source

All Articles