This post originated from an RSS feed registered with Java Buzz
by Simon Brown.
Original Post: Object instantiation in Java is fast!
Feed Title: Simon Brown's weblog
Feed URL: http://www.simongbrown.com/blog/feed.xml?flavor=rss20&category=java
Feed Description: My thoughts on Java, software development and technology.
I'm putting together a prototype for a file adapter component at the moment that reads in a file containing hundreds of thousands of rows and dispatches each item in the file for processing. Out of curiosity I ran some benchmarks on my work PC - a Pentium 4, 2Ghz, 1Gb RAM running Windows XP. Reading a file containing 200,000 lines with a BufferedReader takes less than a second using the original java.io libraries. Pretty quick, and I wonder how long the file would take to read in with memory-mapped files in NIO.
However, what really interested me was the overhead incurred by wrapping each line in the file inside a new object. The reason for doing this was so that each line looked like a domain object, making it cleaner to pass around and easier extract information. So, after commenting out this object instantiation, I re-ran the benchmark. It only took <100ms off the total time to run the program. I am amazed! Only <100ms to create 200,000 objects.
As a test I ran the following code.
long start = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
Integer x = new Integer(i);
}
long end = System.currentTimeMillis();
System.out.println(end-start);
Guesses on how long this took to run? 15ms! Did I miss something here? Is the compiler actually not running this code for some reason? Or is Java just damn fast? I need to run a profiler over this to make sure that the objects actually are being created!