I am using a queue service that only takes messages as byte so I need to convert my data quickly to the format and then make it back to its original when I receive work from the queue. My data format is a INT, DOUBLE, and INT[] and here’s how I did it at first
//to convert to string
String[] message = { Integer.toString(number), String.valueOf(double), Arrays.toString(my_list) };
message.asString;
//to convert back
String message_without_brackets = message.replace("[", "" ).replace("]", "");
String[] temp_message = message_without_brackets.split(",");
int interger = Integer.valueOf(temp_message[0]);
double double = Double.valueOf(temp_message[1]);
int[] my_list = new int[temp_message.length-2]; //-2 because the first two entries are other data
for (int i = 2; i < temp_message.length; i++) {
my_list[i-2] = Integer.parseInt(temp_message[i].replace(" ",""));
}
This is super ugly and it annoyed me that after a few weeks(or a single night of heavy drinking) I would probably not be able to figure out this quickly. Performance wise the code wasn’t too bad, I think replace was the heaviest part of the code(if I remember it was like 15% of overall execution).
I asked around and found Gson to be able to do this cleaner but the performance is now over 40% of my loop now(its Gson itself thats doing it):
Gson gson = new Gson();
int[] sub = { 0, 59, 16 };
Object[] values = { 0, 43.0, sub };
String output = gson.toJson(values); // => [0, 43.0,[0,59,16]]
Object[] deserialized = gson.fromJson(output, Object[].class);
System.out.println(deserialized[0]);
System.out.println(deserialized[1]);
System.out.println(deserialized[2]);
So I’m wondering if there’s faster way to get the same result?I am trying out a few of the suggestions in this question but is there a faster way to do this without depending on any external libraries as my needs are quite simple(if not, then is there a fast one)? Because someone suggested Gson, I looked at Json parsers, but is that what I should be looking for or is are there other types of libraries that do this?
EDIT: I am converting it to string because I thought I needed to do that to send it as getBytes(), is there any other format that would be faster that I can use getBytes() on?
You can use a DataOutputStream like
If you want to get more extreme you can use recycled ByteBuffers or even direct ByteBuffers and use native byte ordering. etc.