• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Array vs arraylist

 
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic