闲来无事,将java中判断数组中包含某个元素的几种方式的速度进行对比,直接上代码
talk is cheap, show you the code
package test.contain.lishaojie;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TestContain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arr = new String[] { "DD", "CC", "DD", "FF", "KK"};
String target ="A";
int times = 1000;//次数
//转换成list方式
long startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
ByList(arr, target);
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("list方式: " + duration / 1000000);
//转换成set方式
startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
BySet(arr, target);
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("set方式: " + duration / 1000000);
//直接循环方式
startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
ByForLoop(arr, target);
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("循环方式: " + duration / 1000000);
//二分法查找
startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
ByArraysBinarySearch(arr, target);
}
endTime = System.currentTimeMillis();
duration = endTime - startTime;
System.out.println("二分法查找: " + duration / 1000000);
}
public static boolean ByList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
public static boolean BySet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
public static boolean ByForLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
public static boolean ByArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}
}
运行结果如下:
list方式: 5
set方式: 22
循环方式: 2
二分法查找: 3
经过大量数据测试循环方式效率最高,其次是二分法,最后是list,和set因为因为将数组压入Collection类型中,首先要将数组元素遍历一遍,然后再使用集合类做其他操作。但是list方式明显要比set方式快很多,这是为什么呢?直接看代码:首先
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
返回的是ArrayList所以set方式还要进行一次操作将ArrayList转换成set,
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
之一addAll方法:
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
又一次进行了选环,所以效率比较低,binggo