My Scala server gets InputStream object from socket by socket.getInputStream (some bytes sent from my socket client, the size of bytes is printed below)
And following code tries to read it to Array
var buffer: Array[Byte] = null
def read(stream: InputStream, size: Int) = {
val start = System.nanoTime()
buffer = new Array[Byte](size)
var value: Int = 0
(0 until size).foreach(i => {
value = stream.read()
buffer(i) = value.toByte
})
val end = System.nanoTime()
println(s"Getting buffer from InputStream, size: $size, cost: ${(end - start)/1e6} ms")
buffer
}
Part of output is
Getting buffer from InputStream, size: 4, cost: 174.923596 ms
Getting buffer from InputStream, size: 2408728, cost: 919.207885 ms
However, for the same data size, some existed server could be much faster, e.g. Redis could send the bytes in ~10ms, so
Is it possible to improve the performance in this Program?
Sourcefrom the stdlib.