I would like to know which representation of a String (normal String or byte-array) would require more memory to be stored?
A byte-array representation is available to me in my code. Should I convert this to a String before transferring it over the network (in response to an AJAX call)?
-
if it's already in byte format and you don't need it in a String form, then there's no need to convert it to a String. I'm not sure what your goals are, but it seems like you want to optimise prematurely? If you're worried about memory you wouldn't be using Java.user1244949– user12449492015-11-27 13:03:58 +00:00Commented Nov 27, 2015 at 13:03
-
1. can't be answered since it depends on too many things. 2. When you transfer something over the network it must be turned into bytes, therefore the answer is no, just use the byte representation.wero– wero2015-11-27 13:06:16 +00:00Commented Nov 27, 2015 at 13:06
-
6@WalterM do you suggest that Java developers do not feel concerned by memory management?dotvav– dotvav2015-11-27 13:06:36 +00:00Commented Nov 27, 2015 at 13:06
-
String in java holds Unicode by design (=can hold all combinations of scripts). Using chars of 2 bytes, UTF-16. As bytes must be associated with some encoding, conversion to bytes must indicate the target encoding, and a conversion will take place. On that basis you can decide yourself.Joop Eggen– Joop Eggen2015-11-27 14:02:41 +00:00Commented Nov 27, 2015 at 14:02
-
Strings are basically a standardized array of bytes, so you can use them easily in your code, not worrying about encoding. An array of bytes is binary, and can contain any encoding.Guillaume F.– Guillaume F.2015-11-27 14:21:06 +00:00Commented Nov 27, 2015 at 14:21
2 Answers
1 => see: What is the Java's internal represention for String? Modified UTF-8? UTF-16?
2 => multiple options if it's short, simply transfer a string if it's ascii, otherwise, convert it :
String serial= DatatypeConverter.printBase64Binary(bytes)
and you can use GET
decoding is possible with java, php, ...
if it's big, use POST, and binary (or native).
Comments
For 2: If it is a response to an AJAX request most probably you need to send an HTTP response and to send an HTTP response usually, in a Servlet for example, you use an OutputStream object (http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html) or a PrintWriter and use write method to write the response.
If you use HttpServletResponse you may directly write a String with a PrintWriter
HttpServletResponse httpServletResponse;
...
String responseToClient = "HOLA";
httpServletResponse.getWriter().write(responseToClient);
If you use method getOutpuStream then you will obtain a SevletOutputStream and write method receives a byte array.