Reputation: 681
I'm just looking for a rough estimate of data in and out of my socket server. I figured using serialize would be the trick since I can count the bytes of an object. I know there's Instrumentation
but don't want to use that. Why is int coming back at 81?!?! Its supposed to be 4 bytes.
I'm no expert on the guts of serialize beside some basics, but I didn't expect 81!
int x = 1;
long test1 = Tools.serialize("1").length; // returns 8
long test2 = Tools.serialize(x).length; // returns 81 ???
private static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
Upvotes: 1
Views: 38
Reputation: 23319
When you call serialize(x)
, x will be boxed to an Integer
object then writeObject
will serialize the entire Integer
object and not the just the value its int
value.
You have to do special treatment for ever type
o.writeInt(x);
o.writeLong(x); etc...
this could be as simple as that
if(obj.getClass().equals(Integer.class)){
Integer i = (Integer) obj;
o.writeInt(i.intValue());
}
else if(obj.getClass().equals(Long.class)){
Long l = (Long) obj;
o.writeLong(l.longValue());
}....
else {
o.writeObject(obj);
}
There are loads of libraries that do serialisation stuff with backward and forward compatibilities, pick one
Upvotes: 1
Reputation: 2970
Because you are passing it as an object not as a primitive data type, you should actually use o.writeInt(val)
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeInt(1);
System.out.println(b.toByteArray().length); //4
So what you should do is to write multiple methods for it like
serialize(int num){...}
serialize(Object obj){...}
also this might be interesting http://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html
Upvotes: 1