For generating new objects, we often use new, but new does not look so fast, it seems to be a very resource-friendly operation, and clone looks much better than new, and the program contrasts:
First set up a test class to perform new and clone operations on this class, Test1.java:
Public class Implements cloneable{ String str; Public Test1 (String str) { this. str=str; } Public throws clonenotsupportedexception{ return (Test1)Super. Clone ();} }
Main program launch test: 10 million new and clone, respectively, to see the time spent:
Public classClonetest { Public Static voidMain (string[] args)throwsclonenotsupportedexception {Longt1=System.currenttimemillis (); for(inti=0;i<10000000;i++) {Test1 S1=NewTest1 ("Test"); } LongT2=System.currenttimemillis (); Test1 S1=NewTest1 ("Test"); for(intj=0;j<10000000;j++) {Test1 s2=S1.clone (); } Longt3=System.currenttimemillis (); System.out.println (T2-t1); System.out.println (T3-T2); }}
Results:
It can be seen that for such operations, New is about 10 times times more than clone, but for a slightly more complex object? We add some action to the Test1.java construction method: After the modification
public class Test1 implements cloneable{String str; public Test1 (String str) { if (Str.startswith ("R" = "AAAAAAA" ; } str.replaceall ( "es", "AA" this . Str=STR; public Test1 Clone () throws clonenotsupportedexception{ return (Test1) super .clone (); }}
Run again: Result:
It can be seen here that the new operation took a long time, it can be said that the gap is very large, so it is concluded that for lightweight objects, new better, for the construction method of some logical operation of the object, reasonable use of clone can improve performance.
It is important to note that the clone operation is only a shallow clone, cloning the variable value of the cloned object only, not the object that the variable value points to cloning, so the cloning is risky, the operation should be cautious
Comparison of efficiency between Java new and clone