Reputation: 12406
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...
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;
}
}
Upvotes: 2
Views: 96
Reputation: 1461
It really shouldn't make a big deal either way. The first option will create a new file reference every time that its called, so if you call this 100,000 times AND keep the reference to the files, then it might make an impact. Otherwise, it just depends on if it makes sense to have a reference to the Foo objects file, or if Foo is more of a service than an object and its goal is to return any reasonable reference to the file.
Upvotes: 0
Reputation: 7070
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.
Upvotes: 1