杰克逊写的价值太慢了 [英] Jackson writeValueAsString too slow

查看:155
本文介绍了杰克逊写的价值太慢了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从object创建JSON字符串。

I want to create JSON string from object.

ObjectMapper om = new ObjectMapper();
String str = om.writeValueAsString(obj);

有些对象很大,创建JSON字符串需要很长时间。
要创建8MB JSON字符串,它需要大约15秒。

Some objects are large, and it takes long time to create JSON string. To create 8MB JSON string, it needs about 15secs.

如何改善这一点?

推荐答案

确保你有足够的内存:用于存储8 MB序列化JSON的Java字符串需要大约16兆字节的连续内存。

Make sure you have enough memory: Java String for storing 8 MB of serialized JSON needs about 16 megabytes of contiguous memory in heap.

但更重要的是:为什么要在内存中创建 java.lang.String
对于如此巨大的字符串有什么用处?

But more importantly: why are you creating a java.lang.String in memory? What possible use is there for such a huge String?

如果你需要将JSON内容写入文件,那么有不同的方法;类似地写入网络套接字。至少你可以将输出写为 byte [] (减少50%的内存),但在大多数情况下,增量写入外部流只需要很少的内存。

If you need to write JSON content to a file, there are different methods for that; similarly for writing to a network socket. At very least you could write output as a byte[] (takes 50% less memory), but in most cases incremental writing to an external stream requires very little memory.

15秒绝对是非常慢的。没有GC问题,在初始预热之后,Jackson应该在几分之一秒内写出8兆,对于由标准Java类型组成的简单对象,就像10-20毫秒。

15 seconds is definitely very slow. Without GC problems, after initial warmup, Jackson should write 8 megs in fraction of a second, something like 10-20 milliseconds for simple object consisting of standard Java types.

编辑

刚刚意识到在构造结果String期间,临时内存使用量也会增加一倍,因为缓冲内容尚未清除构造字符串。所以8 MB需要至少32 MB来构造String。使用64 MB的默认堆时,这将无法正常工作。

Just realized that during construction of the result String, temporary memory usage will be doubled as well, since buffered content is not yet cleared when String is constructed. So 8 MB would need at least 32 MB to construct String. With default heap of 64 MB this would not work well.

这篇关于杰克逊写的价值太慢了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆