Diego Ramos
Diego Ramos

Reputation: 1059

Most efficient way to generate XML payload in Java

In my application I have a REST endpoint (/processRequest) where I am receiving several parameters (clientId,channelId,opId). These parameters are then used to generate a XML payload with this structure:

<eCommerceDoc>
   <clientId>5</clientId>
   <channelId>2</channelId>
   <opId>opIdString</opId>
</eCommerceDoc>

In the code it looks like this:

@RestController public class RequestController {

@RequestMapping(value="/processRequest")
public String processRequest(
        @RequestParam("clientId")int clientId,
        @RequestParam("channelId")int channelId,
        @RequestParam("opId")String opId
        
        ) {

    String xml = 
            "<eCommerceDoc>" 
            +"<clientId>" + clientId + "</clientId>" 
            +"<channelId>" + channelId + "</channelId>" 
            +"<opId>" + opId + "</opId>" 
            +"</eCommerceDoc>";

    sendXMLtoAnotherSystem(xml);

The problem with this is that the memory is getting filled really fast, I can see that for each request to this endpoint a new String is saved in memory:

enter image description here

In this image we can see that last 2 Strings are the ones which are interned, and first 2 were generated because I triggered 2 requests for this example.

The problem is when doing stress testing, even without a big load these Strings are filling the heap too quickly, causing a lot of Minor Gcs, so my question is if there is a better approach to generate the XML dinamically (using SAX or some framework)? All the questions I have found are about Parsing but in this case I need to generate the actual XML because it is sent to another System. Thanks for the help.

Upvotes: 0

Views: 241

Answers (1)

Michael Kay
Michael Kay

Reputation: 163322

Before you worry about the performance of this code, you should worry about its correctness. At present it's wrong: it fails to look for special characters such as "&" and "<" in the data and escape them as XML requires. We get a lot of posts on StackOverflow from people asking how to repair XML that's been generated carelessly like this!

It's better to generate XML using a library rather than just by string concatenation, even though it won't give you a performance improvement for tiny XML documents like this - though it might if you start generating XML documents that are more substantial.

Upvotes: 1

Related Questions