package com.mindprod.example;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import static java.lang.System.*;
/**
* Test relative speed of 3 methods of looking up a key to see if item is in the list of legal keys.
* <p/>
* HashSet, binary search, linear search for different numbers of keys n.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2008-02-15
* @since 2008-02-15
*/
@SuppressWarnings( { "UnusedAssignment" } )
public class TestWaysOfFinding
{
/**
* random number generator
*/
private static final Random wheel = new Random();
/**
* lookup the random strings
*/
private static HashSet<String> h;
/**
* list of strings we want to look up
*/
private static String[] keys;
/**
* build lookup structure
*/
private static void build()
{
h = new HashSet<>( Arrays.asList( keys ) );
Arrays.sort( keys );
}
/**
* find all the keys by BinarySearch
*/
private static void findAllViaBinarySearch()
{
for ( String lookFor : keys )
{
int whereFound = Arrays.binarySearch( keys, lookFor );
}
}
/**
* find all the keys by HashSet
*/
private static void findAllViaHashSet()
{
for ( String lookFor : keys )
{
boolean found = h.contains( lookFor );
}
}
/**
* find all the keys by linear search
*/
private static void findAllViaLinearSearch()
{
for ( String lookFor : keys )
{
boolean found = false;
for ( String candidate : keys )
{
if ( lookFor.equals( candidate ) )
{
found = true;
break;
}
}
}
}
/**
* generate N random keys
*
* @param n how many keys to generate
*/
private static void generate( int n )
{
keys = new String[ n ];
for ( int i = 0; i < n; i++ )
{
keys[ i ] = Long.toString( wheel.nextLong() );
}
}
/**
* main method. Compare speeds of lookup methods.
*
* @param args not used
*/
public static void main( String[] args )
{
for ( int n = 1; n <= 10000; n *= 10 )
{
generate( n );
build();
final long t1 = System.nanoTime();
findAllViaBinarySearch();
final long t2 = System.nanoTime();
findAllViaHashSet();
final long t3 = System.nanoTime();
findAllViaLinearSearch();
final long t4 = System.nanoTime();
out.println( "n:" +
n +
" binary search: " +
( t2 - t1 ) +
" HashSet: " +
( t3 - t2 ) +
" Linear: " +
( t4 - t3 ) );
}
}
}