Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead vs. Speed of Code (java.io.File array vs. java.lang.String array)

just trying to sort out a small delimma I'm having here.

Currently, I'm working on an application that involves gathering a list of files into memory, to be deleted. Now, at this point, I thought that a java.io.File array would perhaps take up too much memory, since the list of Files in this context could be in the hundreds of possible entries.

Rather than eat excessive amounts of memory up with a list of File objects, I figured that gathering a list of filenames and storing them as a java.lang.String would be cheaper to memory. Now, here's my problem: With the goal in mind that these files are to be deleted, which of these would be cheaper:

  1. Storing an array of File objects rather than String objects, and calling .delete(); on each one in a loop (too much memory used).
  2. Storing an array of String objects with the filenames, but for each iteration of the loop, create a new File object using the list of filenames, and call .delete(); on that file (which means each time the loop iterates, a new File object is created and destroyed--possibly too much processor power being used).

I want to make the program as fast as possible, so either approach has its merits, and I just want to see which of these has the least overhead. Thanks in advance!

like image 281
wpreston Avatar asked May 10 '11 15:05

wpreston


People also ask

Are arrays faster than lists in Java?

An Array is a collection of similar items. Whereas ArrayList can hold item of different types. An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows.

How do you create an array of strings in Java?

The String Array is initialized at the same time as it is declared. You can also initialize the String Array as follows: String[] strArray = new String[3]; strArray[0] = “one”; strArray[1] = “two”; strArray[2] = “three”; Here the String Array is declared first.


1 Answers

The java.io.File represents the filename information/metadata about an entry in the filesystem, it does not contain the contents of the file.

In other words, code like new File("somelarge.txt") does not load the somelarge.txt file into memory.

The only real data that each File object contains is a String path to the File (along with a transient int prefixLength) - consider the File class merely a wrapper around the String path that knows how to invoke all of the filesystem operations.

The best choice here, barring some other requirements, is the code that is the easiest to read and conveys your intent the best.

like image 78
matt b Avatar answered Sep 19 '22 14:09

matt b