tags:

views:

276

answers:

3

For content type "text/plain" which of the following is more efficient if I have to send huge data.

ServletOutputStream sos = response.getOutputStream();

sos.write(byte[])
//or
sos.println("")

Thanks

+4  A: 

That depends on the format you have your source data in.

If it's a String, you're likely going to get better performance using response.getPrintWriter().print() - and it's most certainly going to be safer as far as encoding is concerned.

If it's a byte array then ServletOutputStream.write(byte[]) is likely the fastest as it won't do any additional conversions.

The real answer, however, to this and all other "which is faster" questions is - measure it :-)

ChssPly76
+3  A: 

After quickly looking at Sun's implementation of both OutputStream.write(byte[]) and ServletOutputStream.println(String), I'd say there's no real difference. But as ChssPly76 put it, that can only be verified by measuring it.

Eemeli Kantola
A: 

The most efficient is writing an InputStream (which is NOT in flavor of a ByteArrayInputStream).

Simply because each byte of a byte[] eats exactly one byte of JVM's memory and each character of a String eats that amount of bytes from JVM's memory the character takes in space. So imagine you have 128MB of available heap memory and the "huge" text/plain file is 1.28MB in size and there are 100 users concurrently requesting the file, then your application will crash with an OutOfMemoryError. Not really professional.

Have the "huge" data somewhere in a database or on the disk file system and obtain it as an InputStream the "default way" (i.e. from DB by ResultSet#getBinaryStream() or from disk by FileInputStream) and write it to the OutputStream through a bytebuffer and/or BufferedInputStream/BufferedOutputStream.

An example of such a servlet can be found here.

Good luck.

BalusC