jQuery in Action
[Logo] JavaRanch » JavaRanch Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Reply Bookmark it! Watch this topic JavaRanch » Forums » Java » Performance
 
RSS feed
 
New topic
Author

Array vs arraylist

fahad siddiqui
Ranch Hand

Joined: Jun 14, 2006
Messages: 85

I had a 7mb file. I read the file, parsed its records, made an object out every line and stored in arraylist. It threw memory exceeded exception.
I used an array of 60000 size and read all the lines, parsed and stored in the array.
The process completed in 1 sec.

Why is there such a large difference in performance between these two?
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Messages: 1970

That's not really a difference in performance, is it? One worked, and the other didn't!

If you do not pre-size your ArrayList, it starts off with tiny internal array, and re-sizes the array each time it becomes full. To do that, it creates a bigger array (Java arrays cannot actually be resized), and copies the old contents into it, before discarding the old array. So it briefly has to have enough memory for the old and new arrays. Also, the new array is necessarily bigger than the current size.

You can make ArrayList more memory-efficient and faster by pre-sizing it. That is, specifying an appropriate size when constructing the ArrayList. Presumably, if 60000 was enough for your array-based solution, the same size is suitable for the ArrayList solution.

But do you really know in advance how many items there are? If you do, then an array or pre-sized ArrayList are good solutions. If you do not, then your array-based "solution" is not practical, as you cannot choose an appropriate array size. It's for exactly that type of situation that ArrayList was created. (Collections have some other advantages, too).

If you need to use ArrayList, then you may need to increase the maximum heap setting of your JVM. Look up options like -Xmx on the "java[.exe]" command.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
 
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Java » Performance
 
RSS feed
 
New topic
IntelliJ open source