I am developing an Android application. The primary requirement of the application is that it should be efficient in terms of memory. So, which of these should I proceed with?
String batterylevel;
batterylevel = Float.toString(batteryPct);
or
char batterylevel[];
batterylevel = Float.toString(batteryPct).toCharArray();
With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.
So the character array approach remains significantly faster although less so.
An empty String takes 40 bytes—enough memory to fit 20 Java characters.
char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").
In Oracle's JDK a String has four instance-level fields:
That means that each String introduces an extra object reference (the String itself), and three integers in addition to the character array itself. (The offset and character count are there to allow sharing of the character array among String instances produced through the String#substring() methods, a design choice that some other Java library implementers have eschewed.) Beyond the extra storage cost, there's also one more level of access indirection, not to mention the bounds checking with which the String guards its character array.
Strings are immutable. That means once you have created the string, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before GC kicks in which means waste of memory.
With an array, you can explicitly wipe the data after you're done with it: you can overwrite the array with anything you like.
So as far as I can conclude is char[] is better in terms of memory for your case.
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