0

I have to parse a JSON response and return objects which holds its data. But I am not sure which solution is more "memory-friendly":

Method 1: Fields

public class MyElement {

    private int var1;

    public MyElement(int var1) {
        this.var1 = var1;
    }

    public int getVar1() {
        return var1;
    }

}

Method 1.1: Direct access on field.
Method 1.2: Using builders/factories.

Method 2:

public interface MyElement {
    int getVar1();
}

// In Code
return new MyElement() {
    @Override
    public int getVar1() {
        return 5;
    }
}
  • 1
    I wouldn't write such a thing: Use Jackson. It requires that your objects follow the Java Bean standards. Don't worry about memory friendly until you've profiled your app and data tells you there's a problem. – duffymo Sep 05 '15 at 15:23

2 Answers2

0

Side note: public getVar1() does not compile. Any difference between methods 1, 1.1 and 1.2 is negligible (though 1.1 is mutable unless you make your field final), but I would use method 1. This is because, with method 2, a new (anonymous) class is actually created. If this is executed many times, tons of classes are created. Of course, such differences usually wouldn't matter unless on a truly massive scale, so don't make memory an issue when it isn't one.

bcsb1001
  • 2,834
  • 3
  • 24
  • 35
0

I think the Java Bean Standard is a better approach as it followed in most of the implementations in software development.

I have good references links for you below which will explain details about your doubts :

Places where JavaBeans are used?

When would you use the Builder Pattern?

Community
  • 1
  • 1
Ashish Shukla
  • 1,027
  • 16
  • 36