开发者

Memory management for a object that has a file.

开发者 https://www.devze.com 2023-03-23 18:58 出处:网络
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 wondering if someone could explain the best solution for the smallest memory footprint for an object that has a file in the following situation...

  1. There could be 1 to a few hundred Foo classes.
  2. Thread safety will be important down the road.
  3. Not every Foo class's file is accessed every time.
  4. Each file is unique.
  5. 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 getFil开发者_高级运维e(){ 
            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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消