The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2002

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Like A Dog With A Clone

Posted by Matt Gerrans on January 22, 2002 at 12:55 AM

Well, I cranked out a quick 'n' dirty clone() vs. new performance test and, as expected, new was the hands-down winner. By an order of magnitude, no less. Of course, this test is completely unscientific, since there are, as usual, many other factors to consider, such as garbage collection, the Heisenberg Uncertainty Principal and the Coriolis Effect.

Try it yourself:

(After compiling, run it with "java CloneTest new|clone [N]", where you choose to test new or clone. You can optionally specify the number of operations to perform (the default is 10 million).


// CloneSpeed.java

class CloneSpeed implements Cloneable
{

public static void main( String [] args )
{
if( args.length > 0 && (args[0].equals("new") || args[0].equals("clone")) )
{
long start = System.currentTimeMillis();
int loops = 10000000;
if( args.length > 1 )
loops = Integer.parseInt( args[1] );

if( args[0].equals("new") )
newTest( loops );
else if( args[0].equals("clone") )
cloneTest( loops );

System.out.println("That took " + (System.currentTimeMillis()-start)/1000.0 + " seconds." );

}
else
System.out.println("Specify new or clone.");
}

static void newTest( int loops )
{
System.out.println("Doing " + loops + " loops of new..." );
CloneSpeed o = new CloneSpeed();

for( int i = loops; i > 0; i-- )
o = new CloneSpeed();
}

static void cloneTest( int loops )
{
System.out.println("Doing " + loops + " loops of clone()..." );
CloneSpeed o = new CloneSpeed();

for( int i = loops; i > 0; i-- )
try
{
o = (CloneSpeed)o.clone();
}
catch(CloneNotSupportedException cnse)
{
System.out.println( "How could this error ever occur? And why is it a checked exception?" );
}
}
}





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us