開始使用免費開始

比較搜尋演算法的效能

你在一家電商公司擔任軟體開發工程師,正評估不同的搜尋方式來改進商品搜尋功能。到目前為止,公司既有的搜尋機制非常慢,不過你已經成功移除那段延遲。你現在的任務是將新的搜尋方法與舊的方法做比較,證明它在商品目錄搜尋上更有效率。

本練習屬於課程

Java 程式碼最佳化

檢視課程

練習說明

  • 使用新的搜尋方法 linearSearch() 找到目標元素。
  • 接著使用舊的搜尋方法 linearSearchWithDelay() 找到目標元素。
  • 計算兩種搜尋方法的相對效能差異。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class SearchPerformanceTest {
    public static void main(String[] args) {
        int[] array = new int[10000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }
        
        int target = array[7500]; // Target value to search for

        long startRegular = System.nanoTime();
        // Do a search using the new search method
        boolean foundRegular = ____(array, target);
        long endRegular = System.nanoTime();

        long startDelay = System.nanoTime();
        // Do a search using the old search method
        boolean foundDelay = ____(array, target);
        long endDelay = System.nanoTime();
        
        // Calculate the ratio between the old and new methods
        double ratio = (double)(endDelay - startDelay) / (____ - ____);
        
        System.out.println("Linear search with delay is " + ratio + 
                           " times slower than regular linear search");
    }
    
    private static boolean linearSearch(int[] data, int target) {
        for (int i = 0; i < data.length; i++) {
            if (data[i] == target) return true;
        }
        return false;
    }
    
    private static boolean linearSearchWithDelay(int[] data, int target) {
        for (int i = 0; i < data.length; i++) {
            try {
                Thread.sleep(0, 1000); // 1000 nanoseconds delay
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (data[i] == target) return true;
        }
        return false;
    }
}
編輯並執行程式碼