Skip to content

Instantly share code, notes, and snippets.

@ralfstx
Created April 14, 2014 12:07
Show Gist options
  • Save ralfstx/10641850 to your computer and use it in GitHub Desktop.
Save ralfstx/10641850 to your computer and use it in GitHub Desktop.
ArrayVsListBenchmark
/*******************************************************************************
* Copyright (c) 2014 EclipseSource.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Sternberg - initial implementation and API
******************************************************************************/
package com.eclipsesource.calipercharts.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import com.eclipsesource.calipercharts.CaliperRunner;
import com.google.caliper.Param;
import com.google.caliper.SimpleBenchmark;
public class ArrayVsListBenchmark extends SimpleBenchmark {
@Param int size;
@Param String type;
private String[] array;
private List<String> list;
int c;
@Override
protected void setUp() throws IOException {
array = new String[ size ];
if( "ArrayList".equals( type ) ) {
list = new ArrayList<>( size );
} else if( "LinkedList".equals( type ) ) {
list = new LinkedList<>();
} else if( "Vector".equals( type ) ) {
list = new Vector<>( size );
}
for( int i = 0; i < size; i++ ) {
array[ i ] = "item" + i;
list.add( array[ i ] );
}
}
public void time_toArray( int reps ) {
for( int i = 0; i < reps; i++ ) {
dummy( list.toArray() );
}
}
public void time_toArray_with_size( int reps ) {
for( int i = 0; i < reps; i++ ) {
dummy( list.toArray( new String[ list.size() ] ) );
}
}
public void time_toArray_empty_array( int reps ) {
for( int i = 0; i < reps; i++ ) {
dummy( list.toArray( new String[ 0 ] ) );
}
}
public void time_new_ArrayList( int reps ) {
for( int i = 0; i < reps; i++ ) {
dummy( new ArrayList<>( list ) );
}
}
public void time_unmodifiable_Wrapper( int reps ) {
for( int i = 0; i < reps; i++ ) {
dummy( Collections.unmodifiableList( list ) );
}
}
/* prevent compiler from inlining */
protected void dummy( String string ) {
c++;
assert string != null;
}
protected void dummy( Object[] array ) {
c++;
assert array != null;
}
protected void dummy( List<?> list ) {
c++;
assert list != null;
}
public static void main( String[] args ) throws IOException {
new CaliperRunner( ArrayVsListBenchmark.class )
.addParameter( "type", "ArrayList" ) // , "Vector", "LinkedList",
.addParameter( "size", "5", "20" ) // , "100"
.exec();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment