在Java中判斷數組中包含某個元素的幾種方式的比較


閑來無事,將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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM