Repository navigation
Expand file tree
/
Copy pathExpPerformanceTuning.java
More file actions
226 lines (192 loc) · 10.4 KB
/
Copy pathExpPerformanceTuning.java
File metadata and controls
226 lines (192 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
/**
* Performance tuning en Java: JVM flags, String vs StringBuilder,
* object pooling, boxing/unboxing y lazy initialization.
* Cada técnica se mide con System.nanoTime() para comparar.
*/
public class ExpPerformanceTuning {
// ═══════════════════════════════════════════════════════════════
// JVM FLAGS RELEVANTES (se pasan al ejecutar la JVM, no en código)
// ═══════════════════════════════════════════════════════════════
//
// -Xms512m — heap inicial; evita resize frecuente al arrancar
// -Xmx2g — heap máximo; previene OOM inesperados
// -XX:+UseG1GC — G1 GC: bajo pause time, bueno para servicios web (default JDK 9+)
// -XX:+UseZGC — ZGC: sub-ms pauses, ideal para latencia crítica (JDK 15+)
// -XX:MaxGCPauseMillis=200 — objetivo de pausa máxima para G1
// -XX:+PrintGCDetails -Xlog:gc — diagnóstico de GC en producción
// -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heap.hprof
// — vuelca el heap en OOM para análisis post-mortem
// -server — activa optimizaciones JIT agresivas (HotSpot server compiler)
// ═══════════════════════════════════════════════════════════════
// 1. STRING CONCATENATION vs STRINGBUILDER EN LOOPS
// ═══════════════════════════════════════════════════════════════
static long benchmarkStringConcat(int iterations) {
long start = System.nanoTime();
String result = "";
for (int i = 0; i < iterations; i++) {
result += i; // crea un nuevo objeto String en cada iteración — O(n²) en memoria
}
long elapsed = System.nanoTime() - start;
// Previene que el JIT elimine el resultado por dead code elimination
if (result.isEmpty()) System.out.println("vacío");
return elapsed;
}
static long benchmarkStringBuilder(int iterations) {
long start = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++) {
sb.append(i); // amortized O(1), un solo buffer que crece según necesidad
}
String result = sb.toString();
long elapsed = System.nanoTime() - start;
if (result.isEmpty()) System.out.println("vacío");
return elapsed;
}
// ═══════════════════════════════════════════════════════════════
// 2. OBJECT POOLING CON ArrayDeque
// ═══════════════════════════════════════════════════════════════
// Útil cuando la creación del objeto es cara (conexiones, buffers grandes).
// Aquí se simula con objetos simples para ilustrar el patrón.
static class HeavyObject {
private final byte[] buffer = new byte[1024]; // simula objeto con recursos
void reset() { /* limpiar estado para reutilización */ }
}
static class HeavyObjectPool {
private final ArrayDeque<HeavyObject> pool = new ArrayDeque<>();
private final int maxSize;
HeavyObjectPool(int maxSize) {
this.maxSize = maxSize;
// Pre-calentar el pool
for (int i = 0; i < maxSize; i++) pool.push(new HeavyObject());
}
HeavyObject borrow() {
HeavyObject obj = pool.poll();
return obj != null ? obj : new HeavyObject(); // si el pool está vacío, crea uno nuevo
}
void returnToPool(HeavyObject obj) {
if (pool.size() < maxSize) {
obj.reset();
pool.push(obj);
}
// Si el pool está lleno, el GC recoge el objeto descartado
}
}
static long benchmarkWithoutPool(int iterations) {
long start = System.nanoTime();
for (int i = 0; i < iterations; i++) {
HeavyObject obj = new HeavyObject(); // nueva asignación en heap en cada iteración
obj.reset();
}
return System.nanoTime() - start;
}
static long benchmarkWithPool(int iterations, HeavyObjectPool pool) {
long start = System.nanoTime();
for (int i = 0; i < iterations; i++) {
HeavyObject obj = pool.borrow();
obj.reset();
pool.returnToPool(obj);
}
return System.nanoTime() - start;
}
// ═══════════════════════════════════════════════════════════════
// 3. BOXING/UNBOXING — int vs Integer en loops
// ═══════════════════════════════════════════════════════════════
static long benchmarkBoxing(int iterations) {
long start = System.nanoTime();
Long sum = 0L; // Long (objeto), no long (primitivo)
for (int i = 0; i < iterations; i++) {
sum += i; // cada suma: unbox Long → long, suma, box long → Long
}
long elapsed = System.nanoTime() - start;
if (sum < 0) System.out.println("desbordamiento");
return elapsed;
}
static long benchmarkPrimitive(int iterations) {
long start = System.nanoTime();
long sum = 0L; // primitivo, sin autoboxing
for (int i = 0; i < iterations; i++) {
sum += i;
}
long elapsed = System.nanoTime() - start;
if (sum < 0) System.out.println("desbordamiento");
return elapsed;
}
// ═══════════════════════════════════════════════════════════════
// 4. LAZY INITIALIZATION
// ═══════════════════════════════════════════════════════════════
static class EagerService {
// Se inicializa aunque nunca se use — coste en startup
private final List<String> cache = loadFromDatabase();
private List<String> loadFromDatabase() {
// simula carga lenta
return new ArrayList<>(List.of("item1", "item2", "item3"));
}
List<String> getCache() { return cache; }
}
static class LazyService {
private List<String> cache; // null hasta el primer acceso
List<String> getCache() {
if (cache == null) {
cache = loadFromDatabase(); // solo se carga cuando se necesita
}
return cache;
}
private List<String> loadFromDatabase() {
return new ArrayList<>(List.of("item1", "item2", "item3"));
}
}
// Para acceso concurrente, usar double-checked locking con volatile:
static class ThreadSafeLazyService {
private volatile List<String> cache;
List<String> getCache() {
if (cache == null) {
synchronized (this) {
if (cache == null) { // segunda comprobación dentro del lock
cache = new ArrayList<>(List.of("item1", "item2", "item3"));
}
}
}
return cache;
}
}
// ═══════════════════════════════════════════════════════════════
// MAIN — mide y compara
// ═══════════════════════════════════════════════════════════════
public static void main(String[] args) {
final int ITERATIONS = 10_000;
System.out.println("=== Performance Tuning en Java ===\n");
// Warm-up para que el JIT compile antes de medir
benchmarkStringConcat(100);
benchmarkStringBuilder(100);
System.out.println("1. String concatenation vs StringBuilder (" + ITERATIONS + " iter):");
long concatMs = benchmarkStringConcat(ITERATIONS) / 1_000_000;
long sbMs = benchmarkStringBuilder(ITERATIONS) / 1_000_000;
System.out.println(" String += : " + concatMs + " ms");
System.out.println(" StringBuilder: " + sbMs + " ms");
System.out.println("\n2. Object pooling (" + ITERATIONS + " iter):");
HeavyObjectPool pool = new HeavyObjectPool(10);
long noPoolMs = benchmarkWithoutPool(ITERATIONS) / 1_000_000;
long poolMs = benchmarkWithPool(ITERATIONS, pool) / 1_000_000;
System.out.println(" Sin pool: " + noPoolMs + " ms");
System.out.println(" Con pool: " + poolMs + " ms");
System.out.println("\n3. Boxing vs primitivos (" + ITERATIONS + " iter):");
long boxingMs = benchmarkBoxing(ITERATIONS) / 1_000_000;
long primitiveMs = benchmarkPrimitive(ITERATIONS) / 1_000_000;
System.out.println(" Long (boxing) : " + boxingMs + " ms");
System.out.println(" long (prim.) : " + primitiveMs + " ms");
System.out.println("\n4. Lazy initialization:");
long t0 = System.nanoTime();
LazyService lazy = new LazyService();
long createMs = (System.nanoTime() - t0) / 1000;
System.out.println(" LazyService creado en: " + createMs + " µs (sin cargar datos)");
long t1 = System.nanoTime();
lazy.getCache();
long accessMs = (System.nanoTime() - t1) / 1000;
System.out.println(" Primer acceso getCache(): " + accessMs + " µs");
System.out.println("\n=== JVM flags recomendados (ver comentarios en el código) ===");
System.out.println(" -Xms512m -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200");
}
}