简体   繁体   中英

Jackson's ObjectMapper, serialize list

I wrote simple wrapper around Jackson's ObjectMapper which would convert List<?> to String :

public static <T> String listToString(List<T> list) {
    if (list == null) {
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(list);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

However, if I pass empty ArrayList there, mapper.writeValueAsString(list) is executed around 2 seconds. I'm testing in debug in eclipse. Why is it executed for so much time? What am I doing wrong?

A Jackson ObjectMapper is relatively expensive to create, but once created it can be re-used for many conversions very cheaply. Your benchmark is flawed as it includes the ObjectMapper creation time in the measurement. A better benchmark would create one ObjectMapper up front, then perform several hundred or thousand conversions using the same mapper and calculate the average time per conversion. If you do this you'll see much more respectable numbers.

An ObjectMapper instance is thread-safe once fully configured, so it would be safe to do the following (exception handling code ignored for clarity)

public class X {
  private static final ObjectMapper MAPPER = new ObjectMapper();

  public static <T> String listToString(List<T> list) {
    if(list == null) return null;
    else return MAPPER.writeValueAsString(list);
  }
}

It turned out that the problem was in debugger. If I do this in debug mode, it takes code 2-5 seconds to be executed. But if I do the same thing without debugger and log execution time, it is executed within 0,1-0,8 milliseconds - fast enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM