Java 中的 clone( ) 和 new,哪个效率更高?
Java资料站
共 1547字,需浏览 4分钟
·
2021-12-13 03:26
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
- 对象创建的几种方法 -
1.使用new关键字
2.使用clone方法
3.反射机制
以上四种都可以产生java对象
1,3都会明确的显式的调用构造函数
2是在内存上对已有对象的影印 所以不会调用构造函数
- 何为clone()? -
- clone()和new那个更快? -
package com.miivii.javalib;
/**
* Created by ylWang on 2018/6/20 16:36.
*/
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));
}
}
package com.miivii.javalib;
/**
* Created by ylWang on 2018/6/20 16:36.
*/
public class Bean implements Cloneable {
private String name;
private String firstSign;//获取名字首字母
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();
}
}
作者 | iblade
来源 | csdn.net/iblade/article/details/80749148
加锋哥微信: java1239 围观锋哥朋友圈,每天推送Java干货!
评论