Spaces:
Sleeping
Sleeping
File size: 19,924 Bytes
759768a |
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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
/**
* Performance Optimizer
* Advanced performance monitoring and optimization for GreenPlus by GXS
*/
export class PerformanceOptimizer {
constructor() {
this.metrics = new Map();
this.optimizations = new Map();
this.cache = new Map();
this.observers = [];
// Performance thresholds
this.thresholds = {
analysisTime: 5000, // 5 seconds max
imageProcessing: 3000, // 3 seconds max
audioProcessing: 4000, // 4 seconds max
databaseQuery: 1000, // 1 second max
memoryUsage: 100 * 1024 * 1024, // 100MB max
cacheSize: 50 * 1024 * 1024 // 50MB max
};
this.initializeOptimizations();
}
/**
* Initialize performance optimizations
*/
initializeOptimizations() {
// Enable performance monitoring
this.enablePerformanceMonitoring();
// Setup caching strategies
this.setupCaching();
// Initialize lazy loading
this.setupLazyLoading();
// Setup memory management
this.setupMemoryManagement();
console.log('⚡ Performance optimizer initialized');
}
/**
* Enable comprehensive performance monitoring
*/
enablePerformanceMonitoring() {
// Monitor navigation timing
if ('performance' in window && 'getEntriesByType' in performance) {
const navigationEntries = performance.getEntriesByType('navigation');
if (navigationEntries.length > 0) {
const nav = navigationEntries[0];
this.recordMetric('pageLoad', nav.loadEventEnd - nav.fetchStart);
}
}
// Monitor resource loading
if ('PerformanceObserver' in window) {
const resourceObserver = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.name.includes('chunk') || entry.name.includes('.js')) {
this.recordMetric('resourceLoad', entry.duration, entry.name);
}
});
});
resourceObserver.observe({ entryTypes: ['resource'] });
this.observers.push(resourceObserver);
}
// Monitor memory usage
this.startMemoryMonitoring();
}
/**
* Setup intelligent caching system
*/
setupCaching() {
// Analysis result cache with TTL
this.analysisCache = new Map();
this.cacheTimestamps = new Map();
this.cacheTTL = 5 * 60 * 1000; // 5 minutes
// Image processing cache
this.imageCache = new Map();
this.imageCacheSize = 0;
// Audio processing cache
this.audioCache = new Map();
this.audioCacheSize = 0;
// Database query cache
this.dbCache = new Map();
this.dbCacheTimestamps = new Map();
this.dbCacheTTL = 2 * 60 * 1000; // 2 minutes
}
/**
* Setup lazy loading for components and resources
*/
setupLazyLoading() {
// Intersection Observer for lazy loading
if ('IntersectionObserver' in window) {
this.lazyLoadObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadLazyContent(entry.target);
}
});
}, {
rootMargin: '50px'
});
}
}
/**
* Setup memory management
*/
setupMemoryManagement() {
// Periodic cleanup
setInterval(() => {
this.cleanupCache();
this.cleanupMemory();
}, 60000); // Every minute
// Cleanup on page visibility change
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
this.cleanupMemory();
}
});
}
/**
* Monitor memory usage
*/
startMemoryMonitoring() {
if ('memory' in performance) {
setInterval(() => {
const memory = performance.memory;
this.recordMetric('memoryUsed', memory.usedJSHeapSize);
this.recordMetric('memoryTotal', memory.totalJSHeapSize);
// Trigger cleanup if memory usage is high
if (memory.usedJSHeapSize > this.thresholds.memoryUsage) {
this.cleanupMemory();
}
}, 30000); // Every 30 seconds
}
}
/**
* Optimize image analysis performance
*/
async optimizeImageAnalysis(imageSource, analysisFunction) {
const startTime = performance.now();
try {
// Check cache first
const cacheKey = this.generateImageCacheKey(imageSource);
const cached = this.getFromCache('image', cacheKey);
if (cached) {
this.recordMetric('imageCacheHit', performance.now() - startTime);
return cached;
}
// Optimize image before analysis
const optimizedImage = await this.optimizeImage(imageSource);
// Run analysis with timeout
const result = await this.withTimeout(
analysisFunction(optimizedImage),
this.thresholds.imageProcessing
);
// Cache result
this.setCache('image', cacheKey, result);
const duration = performance.now() - startTime;
this.recordMetric('imageAnalysis', duration);
return result;
} catch (error) {
const duration = performance.now() - startTime;
this.recordMetric('imageAnalysisError', duration);
throw error;
}
}
/**
* Optimize audio analysis performance
*/
async optimizeAudioAnalysis(audioData, analysisFunction) {
const startTime = performance.now();
try {
// Check cache first
const cacheKey = this.generateAudioCacheKey(audioData);
const cached = this.getFromCache('audio', cacheKey);
if (cached) {
this.recordMetric('audioCacheHit', performance.now() - startTime);
return cached;
}
// Optimize audio before analysis
const optimizedAudio = await this.optimizeAudio(audioData);
// Run analysis with timeout
const result = await this.withTimeout(
analysisFunction(optimizedAudio),
this.thresholds.audioProcessing
);
// Cache result
this.setCache('audio', cacheKey, result);
const duration = performance.now() - startTime;
this.recordMetric('audioAnalysis', duration);
return result;
} catch (error) {
const duration = performance.now() - startTime;
this.recordMetric('audioAnalysisError', duration);
throw error;
}
}
/**
* Optimize database operations
*/
async optimizeDbOperation(operation, cacheKey = null) {
const startTime = performance.now();
try {
// Check cache if key provided
if (cacheKey) {
const cached = this.getFromCache('db', cacheKey);
if (cached) {
this.recordMetric('dbCacheHit', performance.now() - startTime);
return cached;
}
}
// Run operation with timeout
const result = await this.withTimeout(
operation(),
this.thresholds.databaseQuery
);
// Cache result if key provided
if (cacheKey) {
this.setCache('db', cacheKey, result);
}
const duration = performance.now() - startTime;
this.recordMetric('dbOperation', duration);
return result;
} catch (error) {
const duration = performance.now() - startTime;
this.recordMetric('dbOperationError', duration);
throw error;
}
}
/**
* Optimize image for analysis
*/
async optimizeImage(imageSource) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
try {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Optimize dimensions (max 1920x1080)
const maxWidth = 1920;
const maxHeight = 1080;
let { width, height } = img;
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
width *= ratio;
height *= ratio;
}
canvas.width = width;
canvas.height = height;
// Draw with high quality
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, width, height);
// Convert to optimized format
const optimizedDataUrl = canvas.toDataURL('image/jpeg', 0.9);
resolve(optimizedDataUrl);
} catch (error) {
reject(error);
}
};
img.onerror = reject;
img.src = typeof imageSource === 'string' ? imageSource : URL.createObjectURL(imageSource);
});
}
/**
* Optimize audio for analysis
*/
async optimizeAudio(audioData) {
// For now, return as-is. In a real implementation, this could:
// - Compress audio
// - Normalize volume
// - Remove silence
// - Convert to optimal format
return audioData;
}
/**
* Add timeout to promises
*/
withTimeout(promise, timeoutMs) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)
)
]);
}
/**
* Cache management
*/
setCache(type, key, value) {
const now = Date.now();
switch (type) {
case 'image':
const imageSize = this.estimateSize(value);
if (this.imageCacheSize + imageSize > this.thresholds.cacheSize) {
this.cleanupImageCache();
}
this.imageCache.set(key, value);
this.imageCacheSize += imageSize;
break;
case 'audio':
const audioSize = this.estimateSize(value);
if (this.audioCacheSize + audioSize > this.thresholds.cacheSize) {
this.cleanupAudioCache();
}
this.audioCache.set(key, value);
this.audioCacheSize += audioSize;
break;
case 'db':
this.dbCache.set(key, value);
this.dbCacheTimestamps.set(key, now);
break;
default:
this.cache.set(key, value);
this.cacheTimestamps.set(key, now);
}
}
getFromCache(type, key) {
const now = Date.now();
switch (type) {
case 'image':
return this.imageCache.get(key);
case 'audio':
return this.audioCache.get(key);
case 'db':
const dbTimestamp = this.dbCacheTimestamps.get(key);
if (dbTimestamp && (now - dbTimestamp) < this.dbCacheTTL) {
return this.dbCache.get(key);
}
this.dbCache.delete(key);
this.dbCacheTimestamps.delete(key);
return null;
default:
const timestamp = this.cacheTimestamps.get(key);
if (timestamp && (now - timestamp) < this.cacheTTL) {
return this.cache.get(key);
}
this.cache.delete(key);
this.cacheTimestamps.delete(key);
return null;
}
}
/**
* Cache cleanup
*/
cleanupCache() {
const now = Date.now();
// Cleanup general cache
for (const [key, timestamp] of this.cacheTimestamps.entries()) {
if (now - timestamp > this.cacheTTL) {
this.cache.delete(key);
this.cacheTimestamps.delete(key);
}
}
// Cleanup DB cache
for (const [key, timestamp] of this.dbCacheTimestamps.entries()) {
if (now - timestamp > this.dbCacheTTL) {
this.dbCache.delete(key);
this.dbCacheTimestamps.delete(key);
}
}
}
cleanupImageCache() {
// Remove oldest entries if cache is too large
const entries = Array.from(this.imageCache.entries());
const toRemove = Math.ceil(entries.length * 0.3); // Remove 30%
for (let i = 0; i < toRemove; i++) {
const [key] = entries[i];
this.imageCache.delete(key);
}
this.imageCacheSize = this.imageCacheSize * 0.7; // Approximate
}
cleanupAudioCache() {
// Remove oldest entries if cache is too large
const entries = Array.from(this.audioCache.entries());
const toRemove = Math.ceil(entries.length * 0.3); // Remove 30%
for (let i = 0; i < toRemove; i++) {
const [key] = entries[i];
this.audioCache.delete(key);
}
this.audioCacheSize = this.audioCacheSize * 0.7; // Approximate
}
cleanupMemory() {
// Force garbage collection if available
if (window.gc) {
window.gc();
}
// Clear large caches if memory pressure is high
if ('memory' in performance) {
const memory = performance.memory;
if (memory.usedJSHeapSize > this.thresholds.memoryUsage * 0.8) {
this.imageCache.clear();
this.audioCache.clear();
this.imageCacheSize = 0;
this.audioCacheSize = 0;
}
}
}
/**
* Generate cache keys
*/
generateImageCacheKey(imageSource) {
if (typeof imageSource === 'string') {
return `img_${this.hashString(imageSource)}`;
} else if (imageSource instanceof Blob) {
return `img_${imageSource.size}_${imageSource.type}_${imageSource.lastModified || Date.now()}`;
}
return `img_${Date.now()}_${Math.random()}`;
}
generateAudioCacheKey(audioData) {
if (audioData instanceof Blob) {
return `audio_${audioData.size}_${audioData.type}_${audioData.lastModified || Date.now()}`;
}
return `audio_${Date.now()}_${Math.random()}`;
}
hashString(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash).toString(36);
}
/**
* Estimate object size in bytes
*/
estimateSize(obj) {
const jsonString = JSON.stringify(obj);
return new Blob([jsonString]).size;
}
/**
* Record performance metrics
*/
recordMetric(name, value, details = null) {
const metric = {
name,
value,
details,
timestamp: Date.now()
};
if (!this.metrics.has(name)) {
this.metrics.set(name, []);
}
const metrics = this.metrics.get(name);
metrics.push(metric);
// Keep only last 100 metrics per type
if (metrics.length > 100) {
metrics.shift();
}
// Log performance issues
if (this.isPerformanceIssue(name, value)) {
console.warn(`⚠️ Performance issue: ${name} took ${value}ms`);
}
}
isPerformanceIssue(name, value) {
const thresholds = {
imageAnalysis: 3000,
audioAnalysis: 4000,
dbOperation: 1000,
pageLoad: 5000
};
return thresholds[name] && value > thresholds[name];
}
/**
* Get performance report
*/
getPerformanceReport() {
const report = {
timestamp: new Date().toISOString(),
metrics: {},
cacheStats: this.getCacheStats(),
memoryStats: this.getMemoryStats(),
recommendations: []
};
// Calculate averages and statistics
for (const [name, metrics] of this.metrics.entries()) {
if (metrics.length > 0) {
const values = metrics.map(m => m.value);
report.metrics[name] = {
count: values.length,
average: values.reduce((a, b) => a + b, 0) / values.length,
min: Math.min(...values),
max: Math.max(...values),
latest: values[values.length - 1]
};
}
}
// Generate recommendations
report.recommendations = this.generatePerformanceRecommendations(report);
return report;
}
getCacheStats() {
return {
imageCache: {
size: this.imageCache.size,
sizeBytes: this.imageCacheSize
},
audioCache: {
size: this.audioCache.size,
sizeBytes: this.audioCacheSize
},
dbCache: {
size: this.dbCache.size
},
generalCache: {
size: this.cache.size
}
};
}
getMemoryStats() {
if ('memory' in performance) {
const memory = performance.memory;
return {
used: memory.usedJSHeapSize,
total: memory.totalJSHeapSize,
limit: memory.jsHeapSizeLimit,
usagePercent: (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100
};
}
return null;
}
generatePerformanceRecommendations(report) {
const recommendations = [];
// Check analysis times
if (report.metrics.imageAnalysis?.average > 2000) {
recommendations.push({
type: 'performance',
priority: 'medium',
message: 'Image analysis is slow. Consider optimizing image size or using web workers.',
metric: 'imageAnalysis'
});
}
if (report.metrics.audioAnalysis?.average > 3000) {
recommendations.push({
type: 'performance',
priority: 'medium',
message: 'Audio analysis is slow. Consider preprocessing audio or using streaming analysis.',
metric: 'audioAnalysis'
});
}
// Check memory usage
const memoryStats = this.getMemoryStats();
if (memoryStats && memoryStats.usagePercent > 80) {
recommendations.push({
type: 'memory',
priority: 'high',
message: 'High memory usage detected. Consider clearing caches or reducing data retention.',
metric: 'memory'
});
}
// Check cache efficiency
const cacheStats = this.getCacheStats();
if (cacheStats.imageCache.sizeBytes > this.thresholds.cacheSize * 0.8) {
recommendations.push({
type: 'cache',
priority: 'low',
message: 'Image cache is large. Consider reducing cache size or TTL.',
metric: 'cache'
});
}
return recommendations;
}
/**
* Lazy loading utilities
*/
observeLazyLoad(element) {
if (this.lazyLoadObserver) {
this.lazyLoadObserver.observe(element);
}
}
loadLazyContent(element) {
// Implementation depends on element type
if (element.dataset.src) {
element.src = element.dataset.src;
element.removeAttribute('data-src');
}
if (this.lazyLoadObserver) {
this.lazyLoadObserver.unobserve(element);
}
}
/**
* Cleanup on destroy
*/
destroy() {
// Clear all caches
this.cache.clear();
this.imageCache.clear();
this.audioCache.clear();
this.dbCache.clear();
// Disconnect observers
this.observers.forEach(observer => observer.disconnect());
if (this.lazyLoadObserver) {
this.lazyLoadObserver.disconnect();
}
console.log('⚡ Performance optimizer destroyed');
}
}
// Create singleton instance
export const performanceOptimizer = new PerformanceOptimizer();
// Export optimization functions
export const optimizeImageAnalysis = (imageSource, analysisFunction) => {
return performanceOptimizer.optimizeImageAnalysis(imageSource, analysisFunction);
};
export const optimizeAudioAnalysis = (audioData, analysisFunction) => {
return performanceOptimizer.optimizeAudioAnalysis(audioData, analysisFunction);
};
export const optimizeDbOperation = (operation, cacheKey) => {
return performanceOptimizer.optimizeDbOperation(operation, cacheKey);
};
export const getPerformanceReport = () => {
return performanceOptimizer.getPerformanceReport();
};
export default performanceOptimizer; |