Jesus Gonzalez
Jesus Gonzalez

Reputation: 411

What's more efficient: Class object or Object[] (object array)?

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]));
    }

}

Upvotes: 0

Views: 217

Answers (1)

Duncan McGregor
Duncan McGregor

Reputation: 18177

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

Upvotes: 2

Related Questions