DEV Community

Aldora
Aldora

Posted on

First Initialization and Execution of ObjectMapper.readValue is Slow

I happened to find that first initialization and execution of ObjectMapper.readValue of an application is slow, no matter if I reuse static objectMapper or use new objectMapper instance every time, the first-time cost won't disappear. But overall, static objectMapper is faster than instance.

The first execution would cost about 420ms, however the second only needs 23ms. No matter I execute the static objectMapper first or objectMapper instance, the first one is the longest one.

String json = "{\"name\":\"car2\",\"keyA\":1,\"keyB\":2,\"wheels\":null,\"atomicCounter\":0,\"counter\":0,\"brand\":\"car brand\"}\n";

        // static objectMapper
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<CompletableFuture<Car>> futureList = new ArrayList<>();
        for (int i =0; i < 9; i++) {
            CompletableFuture<Car> future = CompletableFuture.supplyAsync(() -> {
                // JsonUtil.toObject is a method to get static objectMapper and execute 'readvalue'
                return JsonUtil.toObject(json, new TypeReference<Car>() {});
            });
            futureList.add(future);
        }

        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[]{})).join();
        System.out.println("static objectMapper " + stopwatch.toString());


        // instance objectMapper
        Stopwatch stopwatch1 = Stopwatch.createStarted();
        List<CompletableFuture<Car>> futureList2 = new ArrayList<>();
        for (int i =0; i < 9; i++) {
            CompletableFuture<Car> future = CompletableFuture.supplyAsync(() -> {
                Car car = null;
                try {
                    car = new ObjectMapper().readValue(json, new TypeReference<Car>() {});
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return car;
            }).exceptionally(e -> {throw new RuntimeException(e.getMessage());});
            futureList2.add(future);
        }

        CompletableFuture.allOf(futureList2.toArray(new CompletableFuture[]{})).join();
        System.out.println("instance objectMapper " + stopwatch1.toString());
Enter fullscreen mode Exit fullscreen mode

Executable code:
repo

Discussion (0)