Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Copy using Jackson: String or JsonNode

Objective: deep copy (or clone) of a Java object
One of the suggested ways (almost everywhere) to do it is using Jackson:

MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.readValue(mapper.writeValueAsString(myPojo), MyPojo.class);

Question: is the following better? in terms of performance? is there any drawbacks?

MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.treeToValue(mapper.valueToTree(myPojo), MyPojo.class);
like image 640
Rad Avatar asked Apr 18 '18 15:04

Rad


1 Answers

Answered by Tatu Saloranta:

Second way should be bit more efficient since it only creates and uses logical token stream but does not have to encode JSON and then decode (parse) it to/from token stream. So that is close to optimal regarding Jackson.

About the only thing to make it even more optimal would be to directly use TokenBuffer (which is what Jackson itself uses for buffering). Something like:

TokenBuffer tb = new TokenBuffer(); // or one of factory methods
mapper.writeValue(tb, myPojo);
MyPojo copy = mapper.readValue(tb.asParser(), MyPojo.class);

This would further eliminate construction and traversal of the tree model. I don't know how big a difference it'll make, but is not much more code.

Thanks Tatu :)

like image 169
Rad Avatar answered Sep 22 '22 21:09

Rad