Which of clone() and new in Java is more efficient?

Posted by guxin1999 on Tue, 07 Dec 2021 10:08:21 +0100

Several methods of object creation:

  1. Use the new keyword
  2. Using clone method
  3. Reflection mechanism
  4. Deserialization

All four of the above can generate java objects

  • 1 and 3 will explicitly call the constructor
  • 2 is a copy of an existing object in memory, so the constructor will not be called
  • 4 is to restore the class object from the file, and the constructor will not be called

What is clone ()?

  1. The copied object returns a new object, not the reference address of an object;
  2. The copied object already contains the information of the original object rather than the initial information of the object, that is, each copy action is not for the creation of a new object.

clone () and new are faster?

Using clone to copy data blocks in memory and copy existing objects is also a way to generate objects. The premise is that the class implements the clonable interface. The clonable interface has no methods and is an empty interface. Such an interface can also be called a flag interface. Only when the interface is implemented can the clone operation be supported. Some people may ask that all objects in java have a default parent class Object.

There is a clone method in the Object. Why do you have to implement the clonable interface? This is the meaning of the clonable interface flag interface. Only by implementing this interface can the replication operation be realized, because when copying an Object, the jvm will check whether the Object class implements the clonable interface. If it does not implement it, it will report a clonnotsupportedexception exception. Similar interfaces include Serializable interface, RandomAccess interface, etc.

It is also worth mentioning that the constructor is not called when the clone operation is performed. In addition, clone operation will also face the problems of deep copy and shallow copy. On this issue, there is a lot of relevant knowledge on the Internet, so I won't mention it any more. Since the object obtained through the copy operation does not need to call the constructor, it is just a copy of the data block in memory. Will the efficiency of copying the object be faster than that of new.

Answer: No. Obviously, jvm developers also realize that generating objects through new accounts for the vast majority of the objects generated by developers, so they optimize the generation of objects by new operation.

For example:

package com.miivii.javalib;

public class Bean implements Cloneable {
    private String name;

    public Bean(String name) {
        this.name = name;
    }

    @Override
    protected Bean clone() throws CloneNotSupportedException {
        return (Bean) super.clone();
    }
}
package com.miivii.javalib;

public class TestClass {
    private static final int COUNT = 10000 * 1000;

    public static void main(String[] args) throws CloneNotSupportedException {

        long s1 = System.currentTimeMillis();

        for (int i = 0; i < COUNT; i++) {
            Bean bean = new Bean("ylWang");
        }

        long s2 = System.currentTimeMillis();

        Bean bean = new Bean("ylWang");
        for (int i = 0; i < COUNT; i++) {
            Bean b = bean.clone();
        }

        long s3 = System.currentTimeMillis();

        System.out.println("new  = " + (s2 - s1));
        System.out.println("clone = " + (s3 - s2));
    }
}

Print results:

new beat clone, is that true?

Let's do some simple things in the constructor, such as string interception. Just modify the Bean, and the others remain unchanged. See the print again

package com.miivii.javalib;

public class Bean implements Cloneable {
    private String name;
    private String firstSign;//Get first name initials

    public Bean(String name) {
        this.name = name;
        if (name.length() != 0) {
            firstSign = name.substring(0, 1);
            firstSign += "abc";
        }
    }

    @Override
    protected Bean clone() throws CloneNotSupportedException {
        return (Bean) super.clone();
    }
}

Conclusion: new can be used for lightweight objects and clone can be used for other objects.

Source: blog.csdn.net/iblade/article/details/80749148

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2021 latest version)

2.Stop playing if/ else on the full screen. Try the strategy mode. It's really fragrant!!

3.what the fuck! What is the new syntax of xx ≠ null in Java?

4.Spring Boot 2.6 was officially released, a wave of new features..

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Topics: Java