Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is efficient in terms of memory: char[] or String?

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();
like image 388
Rajarshi Sarkar Avatar asked Mar 18 '15 03:03

Rajarshi Sarkar


People also ask

Which is better char array or string?

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.

Which is faster string or char array?

So the character array approach remains significantly faster although less so.

How much memory is a string?

An empty String takes 40 bytes—enough memory to fit 20 Java characters.

Is string [] a char?

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 (").


1 Answers

In Oracle's JDK a String has four instance-level fields:

  • A character array
  • An integral offset
  • An integral character count
  • An integral hash value

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.

like image 95
Dhrumil Shah - dhuma1981 Avatar answered Oct 25 '22 15:10

Dhrumil Shah - dhuma1981