検索アルゴリズムのパフォーマンスを比較する
あなたはEコマース企業のソフトウェア開発者として、商品検索機能を改善するために、さまざまな検索方法を評価しています。これまで会社が使用していた検索の仕組みは非常に低速でしたが、すでにその遅延は解消できました。次のタスクは、新しい検索方法と旧式の方法を比較し、カタログ検索機能においてより効率的であることを証明することです。
この演習はコースの一部です
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;
}
}