I have an update method that is like an infinite loop because is run every frame. Inside this method I get a float and I have to convert it to an string every frame to post the socore in the screen.
I'm using the << operator that allows me to copy the float to an stringstream and then, i use the str() function to get the string value of the stream.
In the header file I declared scoreString
, actualScore
and scoreLabel
.
update(dt){
actualScore += combo;
scoreString.str("");
scoreString << actualScore;
scoreLabel->setString(scoreString.str());
scoreString.clear();
}
actualScore
is the float that I want to convert to a string. For that purpuse, I use the scoreString object that is an stringstream
. To recycle this stringstream
I use the str("")
function that set the value to nothing, and so I don't have to create the object every time that the loop is run.
This code it's used inside a cocos2dx application, and it's runned in IOS and android devices. I'm getting out of memory only in the android devices.
Here is my logCat output, but I think that it wouldn't show nothing new.
01-12 15:35:25.271: D/dalvikvm(13948): GC_FOR_ALLOC freed 297K, 6% free 9580K/10160K, paused 20ms, total 20ms
01-12 15:35:25.321: D/dalvikvm(13948): GC_FOR_ALLOC freed 297K, 6% free 9580K/10160K, paused 20ms, total 20ms
01-12 15:35:25.371: D/dalvikvm(13948): GC_FOR_ALLOC freed 297K, 6% free 9580K/10160K, paused 21ms, total 21ms
01-12 15:35:25.421: D/dalvikvm(13948): GC_FOR_ALLOC freed 297K, 6% free 9580K/10160K, paused 19ms, total 19ms
01-12 15:35:25.472: D/dalvikvm(13948): GC_FOR_ALLOC freed 297K, 6% free 9580K/10160K, paused 18ms, total 18ms
01-12 15:35:25.522: D/dalvikvm(13948): GC_FOR_ALLOC freed 297K, 6% free 9580K/10160K, paused 14ms, total 14ms
01-12 15:35:25.572: D/dalvikvm(13948): GC_FOR_ALLOC freed 298K, 6% free 9581K/10160K, paused 15ms, total 16ms
...
EDIT I changed the code to the suggestions make in comments, but it didn't work. Also I change the while(true) by an update(dt) that is the real method that run this piece of code.
EDIT 2
Here is the sprintf version, as I say, this also consumes a lot of memory. Also I changed the type of actualScore to int. On the header file I declared score as char score[16];
update(dt){
actualScore += combo;
sprintf(score, "%d", actualScore);
scoreLabel->setString(score);
}
The label that I was using was CCLabelTTF that is slow and waste a lot of memory. I started using CCLabelBMFont that is faster, that solved the memory allocation.
I found that at http://www.cocos2d-x.org/wiki/Text_Labels where it explains the use of the different types of labels that cocos2d-x have.