I was wondering if someone could explain the best solution for the smallest memory footprint for an object that has a file in the following situation…
- There could be 1 to a few hundred Foo classes.
- Thread safety will be important down the road.
- Not every Foo class’s file is accessed every time.
- Each file is unique.
- The file in a Foo class may be accessed more than once.
I was planning to profile the solutions below to find the lowest memory footprint and i have a good idea which one would work best but I was interested in some feedback. Solution 1 seems like the best approach but it feels prone to memory leaks the more something accesses the getter. Thoughts?
Solution 1:
public class Foo{
private final String pathToFile;
public class Foo(String pathToFile){
this.pathToFile = pathToFile;
}
public File getFile(){
return new File(pathToFile);
}
}
Solution 2:
public class Foo{
private final File file;
public class Foo(String pathToFile){
this.file = new File(pathToFile);
}
public File getFile(){
return file;
}
}
Solution 3:
public class Foo{
private final String pathToFile;
private File file = null;
public class Foo(String pathToFile){
this.pathToFile = pathToFile;
}
public File getFile(){
if (file == null){
file = new File(pathToFile);
}
return file;
}
}
It all depens on what you want to do with the program, If you need the path in other places then you should have a reference to that. if you need the file, again you would need a reference. Another solution you could do is in the second solution have a method that will return the path:
file.getPath();So overall either the first solution (if you need the path at some point),
or solution 2 if you do not.