Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to convert int to string

I'm creating a game in which I have a main loop. During one cycle of this loop, I have to convert int value to string about ~50-100 times. So far I've been using this function:

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

But it doesn't seem to be quite efficient as I've encountered FPS drop from ~120 (without using this function) to ~95 (while using it).

Is there any other way to convert int to string that would be much more efficient than my function?

like image 552
Piotr Chojnacki Avatar asked Feb 02 '13 11:02

Piotr Chojnacki


People also ask

How do you convert int to string manually?

Using the to_string() Method This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.


1 Answers

It's 1-72 range. I don't have to deal with negatives.

Pre-create an array/vector of 73 string objects, and use an index to get your string. Returning a const reference will let you save on allocations/deallocations, too:

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

const string& smallIntToString(unsigned int val) {
    return smallNumbers[val < smallNumbers.size() ? val : 0];
}
like image 51
Sergey Kalinichenko Avatar answered Sep 19 '22 00:09

Sergey Kalinichenko