0

I'm not sure if a class object to transfer data will be more efficient than an object array.

My goal is to know which option is the most efficient and which option is the best practice.

Consider this is a web application served to thousands of users.

Here the two sample cases:

A)

Model.java

public class Model {
    public Contact getContact(long id)
    {
        // some logic

        return new Contact(...);
    }
}

Contact.java

public class Contact
{
    private long id;
    private String name;
    private String surname;
    private String email;
    private int session;
    private byte[] avatar;

    // Constructor
    public Contact(long id, String name, ...)

    // Getters and Setters
}

B)

Model.java

public class Model {
    public Object[] getContact(long id)
    {
        // some logic
        Object[] myReturningContact = new Object[n];        
        myReturningContact[0] = rs.getLong("id");
        // ...
        myReturningContact[n] = rs.getBytes("avatar");

        return myReturningContact;
    }
}

SomeController.java

public class SomeController
{

    public void someAction()
    {
        // Option A
        this.setSomeTextTo(contact.getName());

        // Option B
        this.setSomeTextTo(String.valueOf(returningObject[n]));
    }

}
4
  • Should performance be a higher consideration than readability in this case? Commented Nov 16, 2015 at 19:19
  • Consider a web application served to thousands of users. Commented Nov 16, 2015 at 19:21
  • I would be surprised if you noticed any material difference... Commented Nov 16, 2015 at 19:22
  • Which is an absurdly trivial volume. A single request routinely generates hundreds of objects. Commented Nov 16, 2015 at 19:23

1 Answer 1

2

Option A is best practice, unless you have a speed requirement that it can't meet, and Option B can.

Note that Option A will probably be a little faster if you make your fields public and final and don't use getters.

Also note that if you have many primitive fields, the cost of boxing and unboxing will slow down Option B, as may String.valueOf on Strings

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.