2

I have created a Pdf in my Java web application and I am sending it as a e-mail attachment. The Pdf is created as a byte[] array. Is it better to wrap it in a ByteArrayInputStream or should I leave it as byte[].

Wrapping it might be better for memory deallocation (read the accepted answer in this thread), but the downside would be that the InputStream (if I am right) creates a copy of the array (read here ).

Which is better to avoid the possibility of having memory hogs?

Community
  • 1
  • 1
Atticus
  • 1,622
  • 7
  • 32
  • 55

1 Answers1

3

No, ByteArrayInputStream wraps the array, it doesn't copy it. From the documentation (of the constructor taking 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.

It's possible that whatever uses the input stream will copy it, but ByteArrayInputStream itself won't.

I'm not convinced that you're really worrying about a particularly important issue - I don't think it would actually create a memory leak at all, just using a byte array.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I was reading an answer that mentioned using byte[] instead of InputStream to save the webapp from memory hogs, and I did not know if that is really an issue. – Atticus Jan 28 '11 at 09:42
  • @Atticus: I certainly wouldn't *assume* it's an issue without understanding why the author of that answer *claimed* it's a "memory hog". I suspect it's to allow the data to stream rather than being all copied into memory - but that may or may not be relevant in your situation. As ever, it's important to understand the context of other answers, and whether that context applies to you. – Jon Skeet Jan 28 '11 at 09:46