← Back to Module 5
Application Optimization
Code Optimization
Algorithm Optimization
// Inefficient algorithm
public int sumArray(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
// Optimized algorithm
public int sumArrayOptimized(int[] arr) {
return Arrays.stream(arr).sum();
}
Loop Optimization
// Inefficient loop
for (int i = 0; i < list.size(); i++) {
process(list.get(i));
}
// Optimized loop
for (String item : list) {
process(item);
}
String Optimization
String Concatenation
// Inefficient concatenation
String result = "";
for (int i = 0; i < 1000; i++) {
result += "Hello";
}
// Optimized concatenation
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("Hello");
}
String result = sb.toString();
String Comparison
// Inefficient comparison
if (str1 == str2) { // Compares references
// ...
}
// Optimized comparison
if (str1.equals(str2)) { // Compares content
// ...
}
Collection Optimization
Collection Initialization
// Inefficient initialization
ArrayList list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add("Item " + i);
}
// Optimized initialization
ArrayList list = new ArrayList<>(1000);
for (int i = 0; i < 1000; i++) {
list.add("Item " + i);
}
Collection Selection
// ArrayList vs LinkedList
// ArrayList: Better for random access
ArrayList arrayList = new ArrayList<>();
// LinkedList: Better for insertions/deletions
LinkedList linkedList = new LinkedList<>();
// HashSet vs TreeSet
// HashSet: Better performance, unordered
HashSet hashSet = new HashSet<>();
// TreeSet: Ordered, more overhead
TreeSet treeSet = new TreeSet<>();
I/O Optimization
File Operations
// Inefficient file reading
FileInputStream fis = new FileInputStream("file.txt");
int b;
while ((b = fis.read()) != -1) {
process(b);
}
// Optimized file reading
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
process(line);
}
}
Network Operations
// Inefficient HTTP client
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
// Process stream
// Optimized HTTP client
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
try (CloseableHttpResponse response = client.execute(request)) {
// Process response
}
}
Concurrency Optimization
Thread Pool Usage
// Inefficient thread creation
for (int i = 0; i < 100; i++) {
new Thread(() -> process()).start();
}
// Optimized thread pool usage
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executor.submit(() -> process());
}
Parallel Processing
// Sequential processing
for (String item : items) {
process(item);
}
// Parallel processing
items.parallelStream().forEach(this::process);