kay
kay

Reputation: 481

Java Object saving

I'm trying to save fairly large classes.

Note:

I am saving and loading using Java's ObjectOutputStream and ObjectInputStream, where in method 1 Integer[] is the object being saved and in method two OutputStream/s buffer (byte[]) is being saved.

What I want the most:

What is the best way for me to save java type classes out of the two following:

Method 1: (IoStreamSerializaion is an interface with the two utilised methods below)

public final class Item implements IoStreamSerialization {

    private int id;

    private int amount;


    public Item(int id, int amount) {
        super();
        this.id = id;
        this.amount = amount;
    }

    @Override 
    public void loadInputStream(InputStream is) {
        id = is.readUnsignedByte();
        amount = is.readInt();
    }

    @Override 
    public OutputStream saveOutputStream() {
        OutputStream os = new OutputStream(2);
        os.writeByte(id);
        os.writeInt(amount);
        return os;
    }

}

Method 2: (IoBinary is an interface with the two utilised methods below, where generic type arg is what to save)

public final class Item implements IoBinary<Integer[]> {

    private int id;

    private int amount;


    public Item(int id, int amount) {
        super();
        this.id = id;
        this.amount = amount;
    }

    @Override 
    public void loadBinary(Integer[] binary) {
        id = binary[0];
        amount = binary[1];
    }

    @Override 
    public Integer[] saveBinary() {
        return new Integer[] { id, amount };
    }

}

Upvotes: 0

Views: 53

Answers (2)

Burkhard
Burkhard

Reputation: 14738

When it comes to performance: "DO NOT GUESS, MEASURE!"

However, first make it run. If it is fast enough, stop there. If not profile and find the bottleneck.

What you should want the most:

  1. Code that is working correctly (i.e. tested)
  2. easy for others to understand
  3. easy to edit after adding or removing from the class
  4. ....
  5. ....
  6. speedy saving and loading during runtime

Points 2. and 3. are related to maintainability are more important than speed. Why? If you have code working correctly and is easy to maintain and change it can also be changed more easily to run faster once the bottleneck is found.

On the other hand, if you have speedy code that is hard to understand and change it will soon start to rot and fester.

Upvotes: 1

Sarath Kumar
Sarath Kumar

Reputation: 36

Implementing with Serialization(Solution 1) is the best and optimal way for large classes, in terms of speedy process and retrieval

Upvotes: 0

Related Questions