java通过原型创建对象真的比new创建对象快吗

1、前几日看原型模式时,原型模式的优势:从内存中直接二进制数据拷贝;不受构造器约束(不会执行构造器)。所以性能和速度要比通过new创建出对象好,真的是这样?(spring框架中配置文件管理也可以设置原型和单例)

2、测试源代码:


/**
 * 通过原型创建对象 真比 通过new创建对象快吗 
 * 测试类
 */
public class TestMain {

    public static void main(String[] args) {
        long startTime=System.currentTimeMillis(); // 获取当前毫秒数
        long endTime=0L;
        
        int size=10000000; // 100万
//        createBeanForNew(size); // 通过new 创建对象。通过注释“此行代码”测试通过原型创建对象所用时间
        createBeanForPrototype(size); // 通过原型创建对象。通过注释“此行代码”测试通过new创建对象所用时间
        
        endTime=System.currentTimeMillis(); // 运行结束后的时间
        System.out.println("程序运行花费:" + (endTime-startTime) +"毫秒");
    }
    
    /**
     * 
     * 通过new 创建实体类
     * @param count
     */
    public static void createBeanForNew(int count){
        PersonBean personBean = new PersonBean("孙悟空", 10000, "花果山水帘洞", "xxxx-yyyyy");
        for (int i = 0; i < count; i++) {
            PersonBean p = new PersonBean("孙悟空", 10000, "花果山水帘洞", "xxxx-yyyyy");
        }
    }
    
    /**
     * 通过原型创建实体类
     * @param count
     */
    public static void createBeanForPrototype(int count){
        PersonBean personBean = new PersonBean("孙悟空", 10000, "花果山水帘洞", "xxxx-yyyyy");
        for (int i = 0; i < count; i++) {
            PersonBean p = personBean.clone();
        }
    }
}

/**
 * 测试实体类
 */
public class PersonBean implements Cloneable{
    private String name; // 姓名
    private int age; // 年龄
    private String address; // 地址
    private String phone; // 电话

    public PersonBean(String name, int age, String address, String phone) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public String getAddress() {
        return address;
    }
    public String getPhone() {
        return phone;
    }
    
    @Override
    protected PersonBean clone(){
        PersonBean personBean = null;
        try {
            personBean = (PersonBean)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return personBean;
    }
}

 

 

3、运行效果

通过原型创建100万个对象所用时间:

通过new创建100万个对象所用时间:

 

4、测试结果明显通过new创建对象要比原型创建对象所用时间少。或者通过构造器初始化数据量时工作量比较大时,用原型效率高?或者……

posted @ 2016-01-04 11:03  车辙草  阅读(1266)  评论(1编辑  收藏  举报