import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.HashSet;
/**
*
* @description: 测试数组查询效率
* @author: zhangxg
*
* @create: 2020-09-15 16:14
**/
public class TestArray {
//使用List
public static boolean useList(String[] arr,String targetValue){
return Arrays.asList(arr).contains(targetValue);
}
//使用Set
public static boolean useSet(String[] arr,String targetValue){
return new HashSet(Arrays.asList(arr)).contains(targetValue);
}
//使用循环判断
public static boolean useLoop(String[] arr,String targetValue){
for(String s:arr){
if(s.equals(targetValue)){
return true;
}
}
return false;
}
//查找有序数组中是否包含某个值的用法
public static boolean useArraysBinarySearch(String[] arr,String targetValue){
int a=Arrays.binarySearch(arr, targetValue);
return a==-1?false:true;
}
//使用ArrayUtils
public static boolean useArrayUtils(String[] arr,String targetValue){
return ArrayUtils.contains(arr,targetValue);
}
public static void main(String[] args) {
String[] arr=new String[]{"CD","BC","EF","DE","AB","JK"};
String targetValue = "A";
//use list
long startTime=System.nanoTime();
int loopSize=Integer.MAX_VALUE;
for(int i=0;i<loopSize;i++){
useList(arr, targetValue);
}
long endTime=System.nanoTime();
long duration=endTime-startTime;
System.out.println("useLoop total:"+duration+" average:"+duration/loopSize);
//use set
long startTime2=System.nanoTime();
for(int i=0;i<loopSize;i++){
useSet(arr, targetValue);
}
long endTime2=System.nanoTime();
long duration2=endTime2-startTime2;
System.out.println("useSet total:"+duration2+" average:"+duration2/loopSize);
//use loop
long startTime3=System.nanoTime();
for(int i=0;i<loopSize;i++){
useLoop(arr, targetValue);
}
long endTime3=System.nanoTime();
long duration3=endTime3-startTime3;
System.out.println("useLoop total:"+duration3+" average:"+duration3/loopSize);
//use Arrays.binarySearch()
long startTime4=System.nanoTime();
for(int i=0;i<loopSize;i++){
useArraysBinarySearch(arr, targetValue);
}
long endTime4=System.nanoTime();
long duration4=endTime4-startTime4;
System.out.println("useArraysBinarySearch total:"+duration4+" average:"+duration4/loopSize);
//使用ArrayUtils
long startTime5=System.nanoTime();
for(int i=0;i<loopSize;i++){
useArrayUtils(arr, targetValue);
}
long endTime5=System.nanoTime();
long duration5=endTime5-startTime5;
System.out.println("useArrayUtils total:"+duration5+" average:"+duration5/loopSize);
}
}
输出结果:
useLoop total:15752174400 average:7
useSet total:261545753500 average:121
useLoop total:16168410100 average:7
useArraysBinarySearch total:14082210900 average:6
useArrayUtils total:15214362300 average:7
结论: 除useSet外其它效率相差并不大