开发者

Writing XML Data to OutputStream with Mutable objects in java

开发者 https://www.devze.com 2023-03-21 22:39 出处:网络
What is the best way to write XML to an OutputStream (TCP Socket) without generating/creating too many Immutable objects?

What is the best way to write XML to an OutputStream (TCP Socket) without generating/creating too many Immutable objects?

So I have my data in a ConcurrentHashMap. I want to loop this data, create a custom XML and then write the XML to an OutputStream. This process will be repetitive and so I dont want to generate too many objects during the conversion/writing process, so that GC doesnt have too much load.

I've been looking at JAXB and XStream, to make the Map to XML conversion easier, but it seems like with the XMLAdapter in JAXB and Convertor approach in XStream, I'll end up with objects created during the conversion process.

I'm willing to roll my own too. I want a solution where I end up reusing mutable objects.

I could use a StringBuffer and concatenate everything (XML tags and my data) using append method and then do mystringBuffer.toString().getBytes() and write the bytearray to the outputstream. In this approach I could reuse StringBuffer and ByteBuffer. Only the bytearray will be a new object each time.

Any other approach?

It seems like I'm getting ahead of my self and assuming that memory/GC could have issues - I could be totally wrong and merely using JAXB or XStream could be the solution. I could then just do some perfor开发者_运维问答mance testing to find out bottleneck.

Thanks


Agreed with skaffman's comment:

I don't think you're giving the garbage collector enough credit - it's extremely good at handling a large number of short-lived objects. Don't worry about object creation overhead until you can see an actual problem with the performance. This question sounds like a classic case of premature optimisation.

So yes, I'd also do some performance testing to see if there is even a bottleneck that you need to be concerned with.

(Primarily posting this answer in an attempt to either get this question some additional attention / competitive answers, or at the least, to simply remove this from the growing list of unanswered questions.)

0

精彩评论

暂无评论...
验证码 换一张
取 消