nimbus_debug
nimbus_debug

Reputation: 650

spring boot RestController JSON serialization cost too much time

I am developing a restful service using latest version of spring boot. Here is a RestController:

@GetMapping(path = "/table")
    public Iterable<Obsidian> getReactTable(@RequestParam Long orderId) {
            long start = System.currentTimeMillis();
            ArrayList<Obsidian> results = new ArrayList<Obsidian>();
            for (Obsidian obs : obsidianRepo.findByOrder(order)) {
                results.add(obs);
            }
            long end = System.currentTimeMillis();
//  Only cost about 300ms
//          System.out.println(end - start);
            return results;
        }
    }

the results list has about 500 Obsidians instances in total.

the Hibernate only cost me 300ms , and the JSON serialization (plus nio and web transfer) cost me 30 seconds!

What may cause Jackson be so slow?

btw: How I found it 30 seconds: I measure it in browser ajax.

Upvotes: 1

Views: 2897

Answers (1)

nimbus_debug
nimbus_debug

Reputation: 650

Short answer: Jackson is fast.

Long answer:

I have to say sorry, I made a big mistake. The POJO serialization is not that simple as I thought, it extends some base entity class, and the base class serialization is doing something slow in the database query.

If you come across the question, check your POJO carefully.

set show-sql=true will help you find out the problem.

Old mistake:

in order to prove that jackson is really slow, I add some code here:

        long start = System.currentTimeMillis();
        ObjectMapper mapper  = new ObjectMapper();
        ArrayList<Obsidian> results = new ArrayList<Obsidian>();
        for (Obsidian obs : obsidianRepo.findByOrder(order)) {
            results.add(obs);
            mapper.writeValueAsString(obs);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);

as you can see, I manually call jackson com.fasterxml.jackson.databind.ObjectMapper in the for loop to see how much time it cost, and the result is: 33247ms, which is exactly the time I measured in browser ajax.

@Test 
public void testJackson() throws JsonProcessingException {

    Obsidian obs = new Obsidian();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValueAsString(obs);
}

I also add a Test in JUnit Test, it cost 0.070s to complete.

as a Gson compare:

@Test 
public void testJackson() throws JsonProcessingException {
    Obsidian obs = new Obsidian();
    Gson gson = new Gson();
    gson.toJson(obs);
}

Gson only cost 0.018s. (still too slow)

Upvotes: 3

Related Questions