Java 'Prototype' pattern - new vs clone vs class.newInstance

前端 未结 6 1073
别那么骄傲
别那么骄傲 2021-02-08 18:11

In my project there are some \'Prototype\' factories that create instances by cloning a final private instance.

The author of those factories says that this pattern prov

6条回答
  •  清歌不尽
    2021-02-08 18:55

    I have created simple benchmark for class Person. I am using latest OpenJDK 8:

    public class Person {
        private String name;
        private int age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    

    And got the following results:

    Benchmark             Mode  Cnt     Score       Error   Units
    
    MyBenchmark.viaClone  avgt   10     10.041 ±    0.059   ns/op
    MyBenchmark.viaNew    avgt   10      7.617 ±    0.113   ns/op
    

    This simple benchmark demonstrates that instantiating new object and setting corresponding properties from source object takes 25% less time than cloning it.

提交回复
热议问题