Porównanie wydajności algorytmów wyszukiwania
Jako programista w firmie e-commerce oceniasz różne metody wyszukiwania, aby usprawnić funkcję wyszukiwania produktów. Dotychczasowy mechanizm wyszukiwania był bardzo wolny, ale udało ci się już usunąć to opóźnienie. Teraz porównaj nową metodę ze starą, żeby udowodnić, że jest bardziej wydajna w przeszukiwaniu katalogu produktów.
To ćwiczenie jest częścią kursu
Optymalizacja kodu w Javie
Instrukcje do ćwiczenia
- Znajdź szukany element, używając nowej metody wyszukiwania:
linearSearch(). - Następnie znajdź ten sam element, używając starej metody:
linearSearchWithDelay(). - Oblicz względną różnicę wydajności obu metod wyszukiwania.
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
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;
}
}