Friday 1 August 2014

Cloning Vs Creating new Object

  1. Using clone, we can initialize the fields of an instance to be identical to the original instance.
  2. In case of creating identical objects cloning is always faster. Instead of reading identical object from database or file, it is always better to create an identical object from existing one.
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BigObject implements Serializable, Cloneable{
    BigInteger id;
    Random rand;
    
    BigObject(){
        rand = new Random();
        id = new BigInteger(100000000, rand);
    }
    
    public static BigObject createObject() throws FileNotFoundException, IOException{
        FileOutputStream fileOut = new FileOutputStream("obj.ser");
        BigObject obj = new BigObject();
        try (ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
             out.writeObject(obj);
        }
        fileOut = null;
        return obj;
    }
    
    @Override
    public BigObject clone() throws CloneNotSupportedException{
        return (BigObject)super.clone();
    }
}

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class CloningVsCreating {
    public static void main(String args[]) throws Exception{
        BigObject obj1 = BigObject.createObject();
        
        long time1 = System.currentTimeMillis();
        FileInputStream fileIn = new FileInputStream("obj.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        BigObject obj2 = (BigObject)in.readObject();
        long time2 = System.currentTimeMillis();
        
        BigObject obj3 = obj1.clone();
        long time3 = System.currentTimeMillis();
        
        System.out.println("Time taken to create new object " + (time2-time1));
        System.out.println("Time to create object using cloning " + (time3-time2));
        
        System.out.println(obj1.id.equals(obj2.id));
        System.out.println(obj1.id.equals(obj3.id));
    }
}

Output
Time taken to create new object 128
Time to create object using cloning 0
true
true




                                                             Home

No comments:

Post a Comment