简体   繁体   English

优化fasterxml ObjectMapper的对象列表

[英]Optimizing fasterxml ObjectMapper for list of Objects

I want to optimizes ObjectMapper for a list. 我想为列表优化ObjectMapper。 The requirement is that I need to add a delimiter after each element of the list. 要求是我需要在列表的每个元素之后添加定界符。 My current code looks like : 我当前的代码如下:

    StringBuilder strBuilder = new StringBuilder();
    for (Event event : segregatedList) {
        String eventJson = mapper.writeValueAsString(event);
        strBuilder.append("\n");
        strBuilder.append(eventJson);

    }

This take a huge amount of time for a long list (~10000 events) .How can I optimize the code to do serializes the list in a single go ? 较长的列表(〜10000个事件)会花费大量时间。如何优化代码以一次序列化列表?

There are multiple ways to concatenate Strings in java. 在Java中有多种连接字符串的方法。

  1. concat() method from java.lang.String java.lang.String中的concat()方法
  2. Using + operator 使用+运算符
  3. Using StringBuffer 使用StringBuffer
  4. Using StringBuilder 使用StringBuilder

From my personal analysis i can say + call on String gets translated into new StringBuilder().append( "" ) . 根据我的个人分析,我可以说+调用String被转换为新的StringBuilder().append( "" ) Since StringBuilder(String) constructor allocates a buffer with 16 char, appending more than 16 characters will require buffer reallocation. 由于StringBuilder(String)构造函数分配的缓冲区包含16个字符,因此追加16个以上的字符将需要重新分配缓冲区。 At last, StringBuffer.toString() calls create a new String object with a copy of StringBuilder buffer. 最后,StringBuffer.toString()调用使用StringBuilder缓冲区的副本创建一个新的String对象。

So if you don't want synchronization overhead StringBuilder stands best among others else i would advice you to use StringBuffer here. 因此,如果您不希望同步开销, StringBuilder在其他应用程序中表现最好,我建议您在这里使用StringBuffer I see you are using StringBuilder already, so there is very little scope for improvement here. 我看到您已经在使用StringBuilder ,因此这里的改进空间很小。 However you can optimize generated json by ignoring properties which are not useful. 但是,您可以通过忽略无用的属性来优化生成的json。

mapper instances are thread-safe, so you can split the mapper.writeValueAsString to a parallel job. 映射器实例是线程安全的,因此您可以将mapper.writeValueAsString拆分为并行作业。 I guess something like this may help if you don't worry of the order in which they are appended! 我想如果您不必担心它们的附加顺序,可能会有所帮助!

segregatedList.parallelStream().map(event -> mapper.writeValueAsString(event)).collect(Collectors.joining("\n")))

Otherwise, I can see very minimum scope of improving here. 否则,我在这里看到的改进范围很小。 Maybe you can optimize json by ignoring properties as mentioned by Dark Knight 也许您可以通过忽略Dark Knight提到的属性来优化json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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