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:
- Storing an array of File objects rather than String objects, and calling .delete(); on each one in a loop (too much memory used).
- 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!
The
java.io.Filerepresents 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 thesomelarge.txtfile into memory.The only real data that each File object contains is a
String pathto the File (along with atransient int prefixLength) – consider theFileclass merely a wrapper around theString paththat 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.