我在 Java Web 应用程序中创建了一个 Pdf,并将其作为电子邮件附件发送。
Pdf 创建为 byte[]
数组。将其包装在 ByteArrayInputStream
中更好还是应该将其保留为 byte[]
。
包装它可能更适合内存释放(阅读this线程中接受的答案),但缺点是InputStream
(如果我是对的)创建数组的副本(阅读here)。
哪个更好地避免内存占用的可能性?
最佳答案
不,ByteArrayInputStream
包装数组,但不复制它。来自 the documentation (构造函数采用byte[]
):
Creates a ByteArrayInputStream so that it uses buf as its buffer array. The buffer array is not copied. The initial value of pos is 0 and the initial value of count is the length of buf.
无论使用输入流,都可能会复制它,但 ByteArrayInputStream
本身不会。
我不相信您真的担心一个特别重要的问题 - 我认为仅仅使用字节数组实际上根本不会造成内存泄漏。
关于Java内存优化(如何避免内存泄漏 - 具体示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4826507/