Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

which is more faster/optimised?

 
Syam Sathyan George
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, can any one tell me which is more optimised and faster.
the first one is a character fetching loop - which i use because i think it has more control - ie; we can call a method when an expected character is found(an escape sequence).



InputStream is;
int total;
int ch,len;
String s;

1)
while(ch = is.read())!= -1)
{
s=String.valueOf((char)ch);
}


2)
total=is.read(byte_array,0,len)
 
Lyx Public
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would say the second one not a worse solution, at least.
Generally speaking the second one should be a better solution. However, the Java spec requires manufacturers to override only the read() method of whatever InputStream. The worst case senarior is that the read(byte[],int,int) method is actually calling read() to do it's job. But you never know that for sure.
So if you know your data length and it's not a monster number, this is ultimately the best way:

byte[] data = new byte[length];
int count = 0;
while(count != data.length) {
in.read(data, count, data.length - count);
}

And if you do NOT know the length. You need to write some more lines to make sure all the bytes are properly read.

Cheers!
 
Syam Sathyan George
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks any more suggestions anyone - the stream that i am reading specifically audio & video (binary)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic