Reputation: 3192
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?
Upvotes: 0
Views: 4453
Reputation: 3192
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.
Upvotes: 0
Reputation: 122414
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);
}
}
Upvotes: 2