Ken Russell from the Java HotSpot VM Group, Sun Microsystems writes in java.net forums:
"Actually in the HotSpot JVM Object.clone() is not currently heavily optimized, while new instance is. You can feel free to file an RFE about this in the bug database. You can work around this problem by overriding clone() and manually allocate the new instance and assign the data into it. In fact, I think this is already probably necessary once your data structures get more complicated, which is why slow performance of Object.clone() hasn't shown up on our performance radar.
P.S. Here's a revised version of your test case which gets rid of startup transients:"
public class Main {
private boolean flag = true;
private String string = "Hello";
private int i = 0;
static class Child extends Main implements Cloneable {
private boolean flag2 = false;
private String string2 = "World";
private int i2 = -1;
}
private static int count = 1000000;
public static void testClone() throws CloneNotSupportedException {
Child child = new Child();
int res = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
Child child2 = (Child) child.clone();
res += child2.i2;
}
long stopTime = System.currentTimeMillis();
System.out.println("" + count + " clones took " +
(stopTime - startTime) + " ms (dummy result = " + res + ")");
}
public static void testNewInstance() {
int res = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
Child child = new Child();
res += child.i2;
}
long stopTime = System.currentTimeMillis();
System.out.println("" + count + " new operations took " +
(stopTime - startTime) + " ms (dummy result = " + res + ")");
}
public static void main(String[] args) throws CloneNotSupportedException {
testClone();
testClone();
testClone();
testNewInstance();
testNewInstance();
testNewInstance();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment