Java中clone( )和new效率哪个更高?
使用new关键字
使用clone方法
反射机制
反序列化
1,3都会明确的显式的调用构造函数
2是在内存上对已有对象的影印 所以不会调用构造函数
4是从文件中还原类的对象 也不会调用构造函数
答案:不是。显然jvm的开发者也意识到通过new方式来生成对象占据了开发者生成对象的绝大部分,所以对于利用new操作生成对象进行了优化。
package com.miivii.javalib; public class Bean implements Cloneable { private String name; public Bean(String name) { this.name = name; } 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 = ; i < COUNT; i++) { Bean bean = new Bean("ylWang"); } long s2 = System.currentTimeMillis(); Bean bean = new Bean("ylWang"); for (int i = ; 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; public class Bean implements Cloneable { private String name; private String firstSign;//获取名字首字母 public Bean(String name) { this.name = name; if (name.length() != ) { firstSign = name.substring(, 1); firstSign += "abc"; } } protected Bean clone() throws CloneNotSupportedException { return (Bean) super.clone(); }}相关文章