aspose file tools*
The moose likes I/O and Streams and the fly likes NIO vs IO Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "NIO vs IO" Watch "NIO vs IO" New topic
Author

NIO vs IO

pawan chopra
Ranch Hand

Joined: Jan 23, 2008
Posts: 413

Hi All,

I have read one tutorial on New IO package of Java. It says that Java NIO is faster than the old IO API. I have tried to find the difference between them using below programs









file.txt has about 30000 lines. When I run Main.java. I am getting below results

Time taken by NIOReader is 7 seconds

Time taken by IOReader is almost 0 seconds


I thought may be its caching the file somewhere so I tried running both of them individually as well. But I am getting the same result. I beleive I am doing something wrong here. Can ant one suggest me what is wrong or if I have misunderstood the whole concept.



Pawan Chopra
SCJP - DuMmIeS mInD
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

[edit]

Actually, most of the time is spent on the for loop. On my system, it takes 14 seconds on a 6MB file, even when I comment out the buffer.get() statement.

The problem is that your code calls the channel.size() method in the for loop. In my case, more than 6 million times.

Call channel.size() once, store it in a variable, and use that variable in the loop.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8997
    
    9

pawan chopra wrote:I have read one tutorial on New IO package of Java. It says that Java NIO is faster than the old IO API.


That's a fast oversimplification. NIO introduced a bunch of functionality that the original java.io classes couldn't handle (see this article). The java.io classes were rewritten with NIO under the covers, so the performance should be similar under most circumstances.
You should also be very cautious about drawing conclusions from microbenchmarks. How the JVM behaves on a small snippet of code is probably not an accurate representation of how it will work in a non-trivial program.

[How To Ask Questions On JavaRanch]
pawan chopra
Ranch Hand

Joined: Jan 23, 2008
Posts: 413

Stephan van Hulst wrote:[edit]
The problem is that your code calls the channel.size() method in the for loop. In my case, more than 6 million times.



Thanks Stephan. You are right channel.size() was the problem. But I am surprise how come fetching size of some object is taking more than 10 seconds? Is it like every time it reads the number bytes from the file?

Joe,

Thanks for the article its great tutorial.
 
 
subject: NIO vs IO