I've been experiencing occasional lags in my Android game when the garbage collector runs. I ran DDMS and discovered that all of the memory being allocated by my application is from this line:
scoreString = String.valueOf(score);
What is the best way to convert an integer to a string without allocating any memory?
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>.
The Integer.toString() method converts int to String. The toString() is the static method of Integer class. The signature of toString() method is given below: public static String toString(int i)
Using __str__() to convert an integer to string in python So, we can directly call the __str__() on the object. In our case we passed integer to str() function in previous example. Instead of it, we can directly call the __str__() function on int object to get a string representation of the integer i.e.
Allocate an array of characters to be displayed as the score, and use a lookup table of 0-9 (this conveniently maps to a 0-base array anyway) to append to this array based on each digit of the score.
Edit: To extract the digits from your score:
12345 mod 10 = 5 12345 mod 100 = 45 / 10 = 4.5 (floors to 4) 12345 mod 1000 = 345 / 100 = 3.45 (floors to 3) 12345 mod 10000 = 2345 / 1000 = 2.345 (floors to 2) 12345 mod 100000 = 12345 / 10000 = 1.2345 (floors to 1)
Also you'll know what the max length for the score character array should be based on whatever you're using to store score (i.e. int)
I recommend reverse-filling this array and initializing it to all '0' so your score will display like
0000000000 0000005127
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With