Mobile Performance Testing Skill
You are an expert in mobile application performance testing. When the user asks you to test mobile app performance, measure launch times, profile memory usage, test under network conditions, or set up mobile performance monitoring, follow these detailed instructions.
Core Principles
- Real device testing over emulators -- Performance measurements on emulators do not represent real-world behavior. Always validate on real devices with representative hardware.
- Cold start and warm start measurement -- Measure both cold start (app loaded from scratch) and warm start (app resumed from background) times. Users experience both.
- Frame rendering performance -- Target 60fps (16.6ms per frame) for smooth UI. Measure jank frames, frozen frames, and total frame drop percentage.
- Memory profiling under load -- Monitor memory allocation, peak usage, and garbage collection frequency during typical and stress scenarios.
- Network-aware performance -- Test on 2G, 3G, 4G, and WiFi conditions. Many users operate on slow or unreliable connections.
- Battery consumption measurement -- Track CPU wake locks, network activity, GPS usage, and background processing that drain battery.
- Baseline comparison -- Every performance test must compare against a baseline from the previous release to detect regressions.
Project Structure
mobile-perf-tests/
android/
launch-time/
cold-start.test.ts
warm-start.test.ts
deep-link-start.test.ts
rendering/
frame-rate.test.ts
scroll-performance.test.ts
animation-jank.test.ts
memory/
memory-leak-detection.test.ts
large-list-memory.test.ts
image-cache-memory.test.ts
network/
slow-network.test.ts
offline-mode.test.ts
large-payload.test.ts
battery/
background-drain.test.ts
location-tracking-drain.test.ts
ios/
launch-time/
cold-start.test.ts
warm-start.test.ts
rendering/
frame-rate.test.ts
scroll-performance.test.ts
memory/
memory-warnings.test.ts
image-cache.test.ts
helpers/
performance-collector.ts
adb-helper.ts
network-throttler.ts
metrics-reporter.ts
baselines/
android-baseline.json
ios-baseline.json
config/
device-profiles.ts
performance-thresholds.ts
reports/
.gitkeep
App Launch Time Testing
// android/launch-time/cold-start.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
interface LaunchMetrics {
coldStartMs: number;
timeToFirstFrameMs: number;
timeToInteractiveMs: number;
totalDrawnFrames: number;
}
describe('Android Cold Start Performance', () => {
const APP_PACKAGE = 'com.example.app';
const LAUNCH_ACTIVITY = '.MainActivity';
const ITERATIONS = 10;
const THRESHOLD_MS = 2000;
it('should launch within threshold on average', async () => {
const measurements: number[] = [];
for (let i = 0; i < ITERATIONS; i++) {
// Force stop the app
await execAdb(`shell am force-stop ${APP_PACKAGE}`);
await sleep(2000);
// Clear app from memory
await execAdb(`shell pm clear ${APP_PACKAGE}`);
await sleep(1000);
// Measure cold start
const output = await execAdb(
`shell am start-activity -W -n ${APP_PACKAGE}/${LAUNCH_ACTIVITY}`
);
const totalTime = parseLaunchTime(output);
measurements.push(totalTime);
}
const average = measurements.reduce((a, b) => a + b, 0) / measurements.length;
const p95 = measurements.sort((a, b) => a - b)[Math.floor(measurements.length * 0.95)];
const max = Math.max(...measurements);
console.log(`Cold start: avg=${average.toFixed(0)}ms, p95=${p95}ms, max=${max}ms`);
expect(average).toBeLessThan(THRESHOLD_MS);
expect(p95).toBeLessThan(THRESHOLD_MS * 1.5);
});
it('should render first frame within 1 second', async () => {
await execAdb(`shell am force-stop ${APP_PACKAGE}`);
await sleep(2000);
const startTime = Date.now();
await execAdb(`shell am start-activity -W -n ${APP_PACKAGE}/${LAUNCH_ACTIVITY}`);
const output = await execAdb('shell dumpsys gfxinfo ' + APP_PACKAGE);
const firstFrameTime = parseFirstFrameTime(output);
expect(firstFrameTime).toBeLessThan(1000);
});
it('should show improvement over baseline', async () => {
const baseline = await loadBaseline('cold-start');
const current = await measureColdStart();
const regression = ((current - baseline) / baseline) * 100;
console.log(`Baseline: ${baseline}ms, Current: ${current}ms, Change: ${regression.toFixed(1)}%`);
expect(regression).toBeLessThan(10); // Allow up to 10% regression
});
});
async function execAdb(command: string): Promise<string> {
const { execSync } = await import('child_process');
return execSync(`adb ${command}`, { encoding: 'utf-8' });
}
function parseLaunchTime(output: string): number {
const match = output.match(/TotalTime:\s*(\d+)/);
return match ? parseInt(match[1], 10) : 0;
}
function parseFirstFrameTime(output: string): number {
const match = output.match(/Janky frames:\s*\d+.*?(\d+)ms/);
return match ? parseInt(match[1], 10) : 0;
}
async function loadBaseline(metric: string): Promise<number> {
const { readFileSync } = await import('fs');
const baselines = JSON.parse(readFileSync('baselines/android-baseline.json', 'utf-8'));
return baselines[metric] || 0;
}
async function measureColdStart(): Promise<number> {
const APP_PACKAGE = 'com.example.app';
const LAUNCH_ACTIVITY = '.MainActivity';
await execAdb(`shell am force-stop ${APP_PACKAGE}`);
await sleep(2000);
const output = await execAdb(`shell am start-activity -W -n ${APP_PACKAGE}/${LAUNCH_ACTIVITY}`);
return parseLaunchTime(output);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Memory Profiling
// android/memory/memory-leak-detection.test.ts
import { describe, it, expect } from 'vitest';
describe('Memory Leak Detection', () => {
const APP_PACKAGE = 'com.example.app';
const THRESHOLD_MB = 200;
it('should not leak memory during navigation cycles', async () => {
const initialMemory = await getAppMemory(APP_PACKAGE);
const memorySnapshots: number[] = [initialMemory];
// Simulate 20 navigation cycles
for (let i = 0; i < 20; i++) {
await navigateToScreen('home');
await navigateToScreen('profile');
await navigateToScreen('settings');
await navigateToScreen('home');
const memory = await getAppMemory(APP_PACKAGE);
memorySnapshots.push(memory);
}
// Force garbage collection
await execAdb(`shell am dumpheap ${APP_PACKAGE} /dev/null`);
await sleep(3000);
const finalMemory = await getAppMemory(APP_PACKAGE);
const memoryGrowth = finalMemory - initialMemory;
console.log(`Memory: initial=${initialMemory}MB, final=${finalMemory}MB, growth=${memoryGrowth}MB`);
// Memory should not grow linearly
expect(finalMemory).toBeLessThan(THRESHOLD_MB);
// Check for linear growth pattern (indicates leak)
const isLinearGrowth = checkLinearGrowth(memorySnapshots);
expect(isLinearGrowth).toBe(false);
});
it('should handle large image lists without OOM', async () => {
await navigateToScreen('image-gallery');
// Scroll through 100 images
for (let i = 0; i < 20; i++) {
await scrollDown();
await sleep(500);
}
const memory = await getAppMemory(APP_PACKAGE);
expect(memory).toBeLessThan(THRESHOLD_MB);
// Check for OOM crashes
const crashes = await getRecentCrashes(APP_PACKAGE);
expect(crashes.filter((c: string) => c.includes('OutOfMemoryError'))).toHaveLength(0);
});
});
async function getAppMemory(packageName: string): Promise<number> {
const output = await execAdb(`shell dumpsys meminfo ${packageName}`);
const match = output.match(/TOTAL\s+(\d+)/);
return match ? parseInt(match[1], 10) / 1024 : 0; // Convert KB to MB
}
function checkLinearGrowth(snapshots: number[]): boolean {
if (snapshots.length < 5) return false;
const diffs = snapshots.slice(1).map((v, i) => v - snapshots[i]);
const avgDiff = diffs.reduce((a, b) => a + b, 0) / diffs.length;
return avgDiff > 2 && diffs.every((d) => d > 0); // Consistent positive growth
}
async function navigateToScreen(screen: string): Promise<void> {
// Use Appium or ADB to navigate
}
async function scrollDown(): Promise<void> {
await execAdb('shell input swipe 500 1500 500 500 300');
}
async function getRecentCrashes(packageName: string): Promise<string[]> {
const output = await execAdb(`shell logcat -d -s AndroidRuntime:E | grep ${packageName}`);
return output.split('\n').filter(Boolean);
}
async function execAdb(command: string): Promise<string> {
const { execSync } = await import('child_process');
return execSync(`adb ${command}`, { encoding: 'utf-8' });
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Network Throttling Tests
// android/network/slow-network.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
describe('Slow Network Performance', () => {
const networkProfiles = {
'3G': { download: 750, upload: 250, latency: 100 },
'2G': { download: 50, upload: 25, latency: 300 },
'slow-wifi': { download: 2000, upload: 1000, latency: 50 },
'lossy': { download: 5000, upload: 2000, latency: 200 },
};
afterAll(async () => {
await disableNetworkThrottling();
});
it('should load main feed within 5s on 3G', async () => {
await setNetworkProfile(networkProfiles['3G']);
const startTime = Date.now();
await navigateToScreen('feed');
await waitForContentLoaded();
const loadTime = Date.now() - startTime;
console.log(`Feed load on 3G: ${loadTime}ms`);
expect(loadTime).toBeLessThan(5000);
});
it('should show loading indicator on slow connections', async () => {
await setNetworkProfile(networkProfiles['2G']);
await navigateToScreen('feed');
// Check that loading indicator is shown
const hasLoadingIndicator = await checkElementVisible('loading-spinner');
expect(hasLoadingIndicator).toBe(true);
});
it('should gracefully handle offline mode', async () => {
await setAirplaneMode(true);
await navigateToScreen('feed');
const hasOfflineMessage = await checkElementVisible('offline-message');
expect(hasOfflineMessage).toBe(true);
await setAirplaneMode(false);
});
it('should retry failed requests on connection recovery', async () => {
await setAirplaneMode(true);
await navigateToScreen('feed');
await setAirplaneMode(false);
await sleep(5000);
const hasContent = await checkElementVisible('feed-content');
expect(hasContent).toBe(true);
});
});
async function setNetworkProfile(profile: { download: number; upload: number; latency: number }): Promise<void> {
// Use ADB network emulation or proxy tool
console.log(`Setting network: ${profile.download}kbps down, ${profile.upload}kbps up, ${profile.latency}ms latency`);
}
async function disableNetworkThrottling(): Promise<void> {
console.log('Disabling network throttling');
}
async function setAirplaneMode(enabled: boolean): Promise<void> {
const { execSync } = await import('child_process');
execSync(`adb shell settings put global airplane_mode_on ${enabled ? 1 : 0}`);
execSync(`adb shell am broadcast -a android.intent.action.AIRPLANE_MODE`);
}
async function navigateToScreen(screen: string): Promise<void> {}
async function waitForContentLoaded(): Promise<void> { await sleep(100); }
async function checkElementVisible(id: string): Promise<boolean> { return true; }
function sleep(ms: number): Promise<void> { return new Promise((r) => setTimeout(r, ms)); }
Frame Rate Performance Testing
// android/rendering/frame-rate.test.ts
import { describe, it, expect } from 'vitest';
interface FrameStats {
totalFrames: number;
jankFrames: number;
frozenFrames: number;
p50RenderTimeMs: number;
p95RenderTimeMs: number;
p99RenderTimeMs: number;
fps: number;
}
describe('Frame Rate Performance', () => {
const APP_PACKAGE = 'com.example.app';
const TARGET_FPS = 60;
const MAX_JANK_PERCENTAGE = 5;
it('should maintain 60fps during list scrolling', async () => {
await resetFrameStats(APP_PACKAGE);
await navigateToScreen('product-list');
// Scroll through the list for 10 seconds
for (let i = 0; i < 20; i++) {
await execAdb('shell input swipe 500 1500 500 300 200');
await sleep(500);
}
const stats = await getFrameStats(APP_PACKAGE);
console.log(`FPS: ${stats.fps}, Jank: ${stats.jankFrames}/${stats.totalFrames}`);
console.log(`Render times: p50=${stats.p50RenderTimeMs}ms, p95=${stats.p95RenderTimeMs}ms, p99=${stats.p99RenderTimeMs}ms`);
expect(stats.fps).toBeGreaterThanOrEqual(TARGET_FPS * 0.9); // Allow 10% margin
const jankPercentage = (stats.jankFrames / stats.totalFrames) * 100;
expect(jankPercentage).toBeLessThan(MAX_JANK_PERCENTAGE);
});
it('should not have frozen frames during navigation', async () => {
await resetFrameStats(APP_PACKAGE);
// Navigate between screens
const screens = ['home', 'search', 'profile', 'settings', 'home'];
for (const screen of screens) {
await navigateToScreen(screen);
await sleep(1000);
}
const stats = await getFrameStats(APP_PACKAGE);
expect(stats.frozenFrames).toBe(0);
});
it('should maintain frame rate during animations', async () => {
await resetFrameStats(APP_PACKAGE);
await navigateToScreen('animations-demo');
// Trigger multiple animations
await execAdb('shell input tap 500 500'); // Trigger animation
await sleep(2000);
await execAdb('shell input tap 500 800'); // Another animation
await sleep(2000);
const stats = await getFrameStats(APP_PACKAGE);
expect(stats.p95RenderTimeMs).toBeLessThan(16.67); // Must be under one frame budget
});
});
async function resetFrameStats(packageName: string): Promise<void> {
await execAdb(\`shell dumpsys gfxinfo \${packageName} reset\`);
}
async function getFrameStats(packageName: string): Promise<FrameStats> {
const output = await execAdb(\`shell dumpsys gfxinfo \${packageName}\`);
const totalMatch = output.match(/Total frames rendered: (\\d+)/);
const jankMatch = output.match(/Janky frames: (\\d+)/);
const frozenMatch = output.match(/Number Missed Vsync: (\\d+)/);
const totalFrames = totalMatch ? parseInt(totalMatch[1], 10) : 0;
const jankFrames = jankMatch ? parseInt(jankMatch[1], 10) : 0;
const frozenFrames = frozenMatch ? parseInt(frozenMatch[1], 10) : 0;
// Parse frame timing histogram
const renderTimes = parseFrameTimings(output);
renderTimes.sort((a, b) => a - b);
return {
totalFrames,
jankFrames,
frozenFrames,
p50RenderTimeMs: percentile(renderTimes, 50),
p95RenderTimeMs: percentile(renderTimes, 95),
p99RenderTimeMs: percentile(renderTimes, 99),
fps: totalFrames > 0 ? Math.round(totalFrames / 10) : 0,
};
}
function parseFrameTimings(output: string): number[] {
const lines = output.split('\\n');
const timings: number[] = [];
let inHistogram = false;
for (const line of lines) {
if (line.includes('HISTOGRAM')) inHistogram = true;
if (inHistogram && line.match(/^\\d/)) {
const parts = line.trim().split(/\\s+/);
if (parts.length >= 2) {
timings.push(parseFloat(parts[0]));
}
}
}
return timings;
}
function percentile(values: number[], p: number): number {
if (values.length === 0) return 0;
const index = Math.ceil(values.length * (p / 100)) - 1;
return values[Math.max(0, index)];
}
async function execAdb(command: string): Promise<string> {
const { execSync } = await import('child_process');
return execSync(\`adb \${command}\`, { encoding: 'utf-8' });
}
async function navigateToScreen(screen: string): Promise<void> {}
function sleep(ms: number): Promise<void> { return new Promise((r) => setTimeout(r, ms)); }
Battery Consumption Testing
// android/battery/background-drain.test.ts
import { describe, it, expect } from 'vitest';
describe('Battery Consumption', () => {
const APP_PACKAGE = 'com.example.app';
it('should not drain more than 2% battery in 30 minutes of background', async () => {
const initialBattery = await getBatteryLevel();
// Launch app and send to background
await execAdb(\`shell am start -n \${APP_PACKAGE}/.MainActivity\`);
await sleep(5000);
await execAdb('shell input keyevent KEYCODE_HOME'); // Send to background
// Wait 30 minutes (or simulated time)
await sleep(30 * 60 * 1000);
const finalBattery = await getBatteryLevel();
const drain = initialBattery - finalBattery;
console.log(\`Battery drain: \${drain}% over 30 minutes\`);
expect(drain).toBeLessThanOrEqual(2);
});
it('should release wake locks when backgrounded', async () => {
await execAdb(\`shell am start -n \${APP_PACKAGE}/.MainActivity\`);
await sleep(5000);
await execAdb('shell input keyevent KEYCODE_HOME');
await sleep(10000);
const wakeLocks = await getAppWakeLocks(APP_PACKAGE);
expect(wakeLocks).toBe(0);
});
});
async function getBatteryLevel(): Promise<number> {
const output = await execAdb('shell dumpsys battery');
const match = output.match(/level: (\\d+)/);
return match ? parseInt(match[1], 10) : 0;
}
async function getAppWakeLocks(packageName: string): Promise<number> {
const output = await execAdb(\`shell dumpsys power | grep \${packageName}\`);
return (output.match(/PARTIAL_WAKE_LOCK/g) || []).length;
}
async function execAdb(command: string): Promise<string> {
const { execSync } = await import('child_process');
return execSync(\`adb \${command}\`, { encoding: 'utf-8' });
}
function sleep(ms: number): Promise<void> { return new Promise((r) => setTimeout(r, ms)); }
App Size Monitoring
// monitoring/app-size.ts
export interface AppSizeReport {
totalSizeMB: number;
downloadSizeMB: number;
installSizeMB: number;
components: Array<{
name: string;
sizeMB: number;
percentage: number;
}>;
thresholdStatus: 'pass' | 'warning' | 'fail';
}
export function analyzeApkSize(apkPath: string): AppSizeReport {
// Analyze APK/AAB components
return {
totalSizeMB: 0,
downloadSizeMB: 0,
installSizeMB: 0,
components: [],
thresholdStatus: 'pass',
};
}
export const APP_SIZE_THRESHOLDS = {
totalMB: { warning: 50, critical: 100 },
downloadMB: { warning: 30, critical: 60 },
dexFilesMB: { warning: 10, critical: 20 },
nativeLibsMB: { warning: 15, critical: 30 },
resourcesMB: { warning: 20, critical: 40 },
};
Best Practices
- Test on real devices with representative hardware -- Low-end and mid-range devices represent the majority of users. Do not only test on flagship phones.
- Measure cold and warm start separately -- Users experience both scenarios. Cold start matters for first impressions; warm start matters for daily usage.
- Run performance tests multiple times -- A single measurement is noisy. Run at least 10 iterations and report median and p95 values.
- Test under realistic network conditions -- Use network throttling to simulate 3G, 4G, and lossy WiFi connections.
- Monitor memory across the entire user session -- Brief memory spikes are acceptable. Continuous growth indicates leaks.
- Establish baselines and track regressions -- Store performance baselines per release and fail tests when regressions exceed thresholds.
- Test with realistic data volumes -- Empty lists and single items do not stress the app. Use hundreds of items with images and complex layouts.
- Include battery impact in performance criteria -- An app that drains 10% battery per hour will get uninstalled regardless of feature quality.
- Automate performance tests in CI -- Run performance tests on every release branch, not just manually before launch.
- Profile before optimizing -- Use Android Profiler and Xcode Instruments to identify actual bottlenecks instead of guessing.
Anti-Patterns
- Only testing on emulators -- Emulator performance does not represent real device behavior. GPU rendering, memory management, and CPU throttling differ significantly.
- Measuring performance once -- Single measurements are unreliable due to JIT compilation, background processes, and thermal throttling. Always aggregate multiple runs.
- Ignoring low-end devices -- Most users do not have flagship phones. Test on devices with 2-3GB RAM and mid-range processors.
- Not testing offline scenarios -- Users frequently lose connectivity. Apps that crash or hang without network are unusable.
- Skipping scroll performance testing -- Janky scrolling is the most user-visible performance issue. Always measure frame rates during scroll.
- Testing only on WiFi -- WiFi performance masks network-dependent bottlenecks. Always include 3G and 4G testing.
- Not monitoring memory during long sessions -- Memory leaks may not appear in 30-second tests. Simulate 5-10 minute user sessions.
- Ignoring app size -- Large APK/IPA files increase download time, storage usage, and initial launch time. Monitor and set size budgets.
- Not testing background behavior -- Apps that consume CPU and network in the background drain battery and may be killed by the OS.
- Comparing performance across different device models -- Always compare same-device measurements across versions, not different devices in the same run.
1---2name: mobile-performance-testing3description: Mobile application performance testing including app launch time, frame rendering, memory profiling, battery consumption, network throttling, and crash analytics using Appium, XCTest, and Espresso with real device testing.4version: 1.0.05author: thetestingacademy6license: MIT7tags: [mobile-performance, app-launch-time, frame-rendering, memory-profiling, battery-testing, network-throttling, appium, espresso, xctest, crash-analytics]8testingTypes: [performance, mobile, e2e, integration]9frameworks: [appium, espresso, xctest, detox]10languages: [typescript, javascript, kotlin, swift]11domains: [mobile, performance, ios, android]12agents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]13metadata:14 source: https://skillmd.com/skills/pramoddutta/mobile-performance-testing15---1617# Mobile Performance Testing Skill1819You are an expert in mobile application performance testing. When the user asks you to test mobile app performance, measure launch times, profile memory usage, test under network conditions, or set up mobile performance monitoring, follow these detailed instructions.2021## Core Principles22231. **Real device testing over emulators** -- Performance measurements on emulators do not represent real-world behavior. Always validate on real devices with representative hardware.242. **Cold start and warm start measurement** -- Measure both cold start (app loaded from scratch) and warm start (app resumed from background) times. Users experience both.253. **Frame rendering performance** -- Target 60fps (16.6ms per frame) for smooth UI. Measure jank frames, frozen frames, and total frame drop percentage.264. **Memory profiling under load** -- Monitor memory allocation, peak usage, and garbage collection frequency during typical and stress scenarios.275. **Network-aware performance** -- Test on 2G, 3G, 4G, and WiFi conditions. Many users operate on slow or unreliable connections.286. **Battery consumption measurement** -- Track CPU wake locks, network activity, GPS usage, and background processing that drain battery.297. **Baseline comparison** -- Every performance test must compare against a baseline from the previous release to detect regressions.3031## Project Structure3233```34mobile-perf-tests/35 android/36 launch-time/37 cold-start.test.ts38 warm-start.test.ts39 deep-link-start.test.ts40 rendering/41 frame-rate.test.ts42 scroll-performance.test.ts43 animation-jank.test.ts44 memory/45 memory-leak-detection.test.ts46 large-list-memory.test.ts47 image-cache-memory.test.ts48 network/49 slow-network.test.ts50 offline-mode.test.ts51 large-payload.test.ts52 battery/53 background-drain.test.ts54 location-tracking-drain.test.ts55 ios/56 launch-time/57 cold-start.test.ts58 warm-start.test.ts59 rendering/60 frame-rate.test.ts61 scroll-performance.test.ts62 memory/63 memory-warnings.test.ts64 image-cache.test.ts65 helpers/66 performance-collector.ts67 adb-helper.ts68 network-throttler.ts69 metrics-reporter.ts70 baselines/71 android-baseline.json72 ios-baseline.json73 config/74 device-profiles.ts75 performance-thresholds.ts76 reports/77 .gitkeep78```7980## App Launch Time Testing8182```typescript83// android/launch-time/cold-start.test.ts84import { describe, it, expect, beforeAll, afterAll } from 'vitest';8586interface LaunchMetrics {87 coldStartMs: number;88 timeToFirstFrameMs: number;89 timeToInteractiveMs: number;90 totalDrawnFrames: number;91}9293describe('Android Cold Start Performance', () => {94 const APP_PACKAGE = 'com.example.app';95 const LAUNCH_ACTIVITY = '.MainActivity';96 const ITERATIONS = 10;97 const THRESHOLD_MS = 2000;9899 it('should launch within threshold on average', async () => {100 const measurements: number[] = [];101102 for (let i = 0; i < ITERATIONS; i++) {103 // Force stop the app104 await execAdb(`shell am force-stop ${APP_PACKAGE}`);105 await sleep(2000);106107 // Clear app from memory108 await execAdb(`shell pm clear ${APP_PACKAGE}`);109 await sleep(1000);110111 // Measure cold start112 const output = await execAdb(113 `shell am start-activity -W -n ${APP_PACKAGE}/${LAUNCH_ACTIVITY}`114 );115116 const totalTime = parseLaunchTime(output);117 measurements.push(totalTime);118 }119120 const average = measurements.reduce((a, b) => a + b, 0) / measurements.length;121 const p95 = measurements.sort((a, b) => a - b)[Math.floor(measurements.length * 0.95)];122 const max = Math.max(...measurements);123124 console.log(`Cold start: avg=${average.toFixed(0)}ms, p95=${p95}ms, max=${max}ms`);125126 expect(average).toBeLessThan(THRESHOLD_MS);127 expect(p95).toBeLessThan(THRESHOLD_MS * 1.5);128 });129130 it('should render first frame within 1 second', async () => {131 await execAdb(`shell am force-stop ${APP_PACKAGE}`);132 await sleep(2000);133134 const startTime = Date.now();135 await execAdb(`shell am start-activity -W -n ${APP_PACKAGE}/${LAUNCH_ACTIVITY}`);136137 const output = await execAdb('shell dumpsys gfxinfo ' + APP_PACKAGE);138 const firstFrameTime = parseFirstFrameTime(output);139140 expect(firstFrameTime).toBeLessThan(1000);141 });142143 it('should show improvement over baseline', async () => {144 const baseline = await loadBaseline('cold-start');145 const current = await measureColdStart();146147 const regression = ((current - baseline) / baseline) * 100;148 console.log(`Baseline: ${baseline}ms, Current: ${current}ms, Change: ${regression.toFixed(1)}%`);149150 expect(regression).toBeLessThan(10); // Allow up to 10% regression151 });152});153154async function execAdb(command: string): Promise<string> {155 const { execSync } = await import('child_process');156 return execSync(`adb ${command}`, { encoding: 'utf-8' });157}158159function parseLaunchTime(output: string): number {160 const match = output.match(/TotalTime:\s*(\d+)/);161 return match ? parseInt(match[1], 10) : 0;162}163164function parseFirstFrameTime(output: string): number {165 const match = output.match(/Janky frames:\s*\d+.*?(\d+)ms/);166 return match ? parseInt(match[1], 10) : 0;167}168169async function loadBaseline(metric: string): Promise<number> {170 const { readFileSync } = await import('fs');171 const baselines = JSON.parse(readFileSync('baselines/android-baseline.json', 'utf-8'));172 return baselines[metric] || 0;173}174175async function measureColdStart(): Promise<number> {176 const APP_PACKAGE = 'com.example.app';177 const LAUNCH_ACTIVITY = '.MainActivity';178 await execAdb(`shell am force-stop ${APP_PACKAGE}`);179 await sleep(2000);180 const output = await execAdb(`shell am start-activity -W -n ${APP_PACKAGE}/${LAUNCH_ACTIVITY}`);181 return parseLaunchTime(output);182}183184function sleep(ms: number): Promise<void> {185 return new Promise((resolve) => setTimeout(resolve, ms));186}187```188189## Memory Profiling190191```typescript192// android/memory/memory-leak-detection.test.ts193import { describe, it, expect } from 'vitest';194195describe('Memory Leak Detection', () => {196 const APP_PACKAGE = 'com.example.app';197 const THRESHOLD_MB = 200;198199 it('should not leak memory during navigation cycles', async () => {200 const initialMemory = await getAppMemory(APP_PACKAGE);201 const memorySnapshots: number[] = [initialMemory];202203 // Simulate 20 navigation cycles204 for (let i = 0; i < 20; i++) {205 await navigateToScreen('home');206 await navigateToScreen('profile');207 await navigateToScreen('settings');208 await navigateToScreen('home');209210 const memory = await getAppMemory(APP_PACKAGE);211 memorySnapshots.push(memory);212 }213214 // Force garbage collection215 await execAdb(`shell am dumpheap ${APP_PACKAGE} /dev/null`);216 await sleep(3000);217218 const finalMemory = await getAppMemory(APP_PACKAGE);219 const memoryGrowth = finalMemory - initialMemory;220221 console.log(`Memory: initial=${initialMemory}MB, final=${finalMemory}MB, growth=${memoryGrowth}MB`);222223 // Memory should not grow linearly224 expect(finalMemory).toBeLessThan(THRESHOLD_MB);225226 // Check for linear growth pattern (indicates leak)227 const isLinearGrowth = checkLinearGrowth(memorySnapshots);228 expect(isLinearGrowth).toBe(false);229 });230231 it('should handle large image lists without OOM', async () => {232 await navigateToScreen('image-gallery');233234 // Scroll through 100 images235 for (let i = 0; i < 20; i++) {236 await scrollDown();237 await sleep(500);238 }239240 const memory = await getAppMemory(APP_PACKAGE);241 expect(memory).toBeLessThan(THRESHOLD_MB);242243 // Check for OOM crashes244 const crashes = await getRecentCrashes(APP_PACKAGE);245 expect(crashes.filter((c: string) => c.includes('OutOfMemoryError'))).toHaveLength(0);246 });247});248249async function getAppMemory(packageName: string): Promise<number> {250 const output = await execAdb(`shell dumpsys meminfo ${packageName}`);251 const match = output.match(/TOTAL\s+(\d+)/);252 return match ? parseInt(match[1], 10) / 1024 : 0; // Convert KB to MB253}254255function checkLinearGrowth(snapshots: number[]): boolean {256 if (snapshots.length < 5) return false;257 const diffs = snapshots.slice(1).map((v, i) => v - snapshots[i]);258 const avgDiff = diffs.reduce((a, b) => a + b, 0) / diffs.length;259 return avgDiff > 2 && diffs.every((d) => d > 0); // Consistent positive growth260}261262async function navigateToScreen(screen: string): Promise<void> {263 // Use Appium or ADB to navigate264}265266async function scrollDown(): Promise<void> {267 await execAdb('shell input swipe 500 1500 500 500 300');268}269270async function getRecentCrashes(packageName: string): Promise<string[]> {271 const output = await execAdb(`shell logcat -d -s AndroidRuntime:E | grep ${packageName}`);272 return output.split('\n').filter(Boolean);273}274275async function execAdb(command: string): Promise<string> {276 const { execSync } = await import('child_process');277 return execSync(`adb ${command}`, { encoding: 'utf-8' });278}279280function sleep(ms: number): Promise<void> {281 return new Promise((resolve) => setTimeout(resolve, ms));282}283```284285## Network Throttling Tests286287```typescript288// android/network/slow-network.test.ts289import { describe, it, expect, beforeAll, afterAll } from 'vitest';290291describe('Slow Network Performance', () => {292 const networkProfiles = {293 '3G': { download: 750, upload: 250, latency: 100 },294 '2G': { download: 50, upload: 25, latency: 300 },295 'slow-wifi': { download: 2000, upload: 1000, latency: 50 },296 'lossy': { download: 5000, upload: 2000, latency: 200 },297 };298299 afterAll(async () => {300 await disableNetworkThrottling();301 });302303 it('should load main feed within 5s on 3G', async () => {304 await setNetworkProfile(networkProfiles['3G']);305306 const startTime = Date.now();307 await navigateToScreen('feed');308 await waitForContentLoaded();309 const loadTime = Date.now() - startTime;310311 console.log(`Feed load on 3G: ${loadTime}ms`);312 expect(loadTime).toBeLessThan(5000);313 });314315 it('should show loading indicator on slow connections', async () => {316 await setNetworkProfile(networkProfiles['2G']);317 await navigateToScreen('feed');318319 // Check that loading indicator is shown320 const hasLoadingIndicator = await checkElementVisible('loading-spinner');321 expect(hasLoadingIndicator).toBe(true);322 });323324 it('should gracefully handle offline mode', async () => {325 await setAirplaneMode(true);326 await navigateToScreen('feed');327328 const hasOfflineMessage = await checkElementVisible('offline-message');329 expect(hasOfflineMessage).toBe(true);330331 await setAirplaneMode(false);332 });333334 it('should retry failed requests on connection recovery', async () => {335 await setAirplaneMode(true);336 await navigateToScreen('feed');337338 await setAirplaneMode(false);339 await sleep(5000);340341 const hasContent = await checkElementVisible('feed-content');342 expect(hasContent).toBe(true);343 });344});345346async function setNetworkProfile(profile: { download: number; upload: number; latency: number }): Promise<void> {347 // Use ADB network emulation or proxy tool348 console.log(`Setting network: ${profile.download}kbps down, ${profile.upload}kbps up, ${profile.latency}ms latency`);349}350351async function disableNetworkThrottling(): Promise<void> {352 console.log('Disabling network throttling');353}354355async function setAirplaneMode(enabled: boolean): Promise<void> {356 const { execSync } = await import('child_process');357 execSync(`adb shell settings put global airplane_mode_on ${enabled ? 1 : 0}`);358 execSync(`adb shell am broadcast -a android.intent.action.AIRPLANE_MODE`);359}360361async function navigateToScreen(screen: string): Promise<void> {}362async function waitForContentLoaded(): Promise<void> { await sleep(100); }363async function checkElementVisible(id: string): Promise<boolean> { return true; }364function sleep(ms: number): Promise<void> { return new Promise((r) => setTimeout(r, ms)); }365```366367## Frame Rate Performance Testing368369```typescript370// android/rendering/frame-rate.test.ts371import { describe, it, expect } from 'vitest';372373interface FrameStats {374 totalFrames: number;375 jankFrames: number;376 frozenFrames: number;377 p50RenderTimeMs: number;378 p95RenderTimeMs: number;379 p99RenderTimeMs: number;380 fps: number;381}382383describe('Frame Rate Performance', () => {384 const APP_PACKAGE = 'com.example.app';385 const TARGET_FPS = 60;386 const MAX_JANK_PERCENTAGE = 5;387388 it('should maintain 60fps during list scrolling', async () => {389 await resetFrameStats(APP_PACKAGE);390 await navigateToScreen('product-list');391392 // Scroll through the list for 10 seconds393 for (let i = 0; i < 20; i++) {394 await execAdb('shell input swipe 500 1500 500 300 200');395 await sleep(500);396 }397398 const stats = await getFrameStats(APP_PACKAGE);399400 console.log(`FPS: ${stats.fps}, Jank: ${stats.jankFrames}/${stats.totalFrames}`);401 console.log(`Render times: p50=${stats.p50RenderTimeMs}ms, p95=${stats.p95RenderTimeMs}ms, p99=${stats.p99RenderTimeMs}ms`);402403 expect(stats.fps).toBeGreaterThanOrEqual(TARGET_FPS * 0.9); // Allow 10% margin404 const jankPercentage = (stats.jankFrames / stats.totalFrames) * 100;405 expect(jankPercentage).toBeLessThan(MAX_JANK_PERCENTAGE);406 });407408 it('should not have frozen frames during navigation', async () => {409 await resetFrameStats(APP_PACKAGE);410411 // Navigate between screens412 const screens = ['home', 'search', 'profile', 'settings', 'home'];413 for (const screen of screens) {414 await navigateToScreen(screen);415 await sleep(1000);416 }417418 const stats = await getFrameStats(APP_PACKAGE);419 expect(stats.frozenFrames).toBe(0);420 });421422 it('should maintain frame rate during animations', async () => {423 await resetFrameStats(APP_PACKAGE);424 await navigateToScreen('animations-demo');425426 // Trigger multiple animations427 await execAdb('shell input tap 500 500'); // Trigger animation428 await sleep(2000);429 await execAdb('shell input tap 500 800'); // Another animation430 await sleep(2000);431432 const stats = await getFrameStats(APP_PACKAGE);433 expect(stats.p95RenderTimeMs).toBeLessThan(16.67); // Must be under one frame budget434 });435});436437async function resetFrameStats(packageName: string): Promise<void> {438 await execAdb(\`shell dumpsys gfxinfo \${packageName} reset\`);439}440441async function getFrameStats(packageName: string): Promise<FrameStats> {442 const output = await execAdb(\`shell dumpsys gfxinfo \${packageName}\`);443444 const totalMatch = output.match(/Total frames rendered: (\\d+)/);445 const jankMatch = output.match(/Janky frames: (\\d+)/);446 const frozenMatch = output.match(/Number Missed Vsync: (\\d+)/);447448 const totalFrames = totalMatch ? parseInt(totalMatch[1], 10) : 0;449 const jankFrames = jankMatch ? parseInt(jankMatch[1], 10) : 0;450 const frozenFrames = frozenMatch ? parseInt(frozenMatch[1], 10) : 0;451452 // Parse frame timing histogram453 const renderTimes = parseFrameTimings(output);454 renderTimes.sort((a, b) => a - b);455456 return {457 totalFrames,458 jankFrames,459 frozenFrames,460 p50RenderTimeMs: percentile(renderTimes, 50),461 p95RenderTimeMs: percentile(renderTimes, 95),462 p99RenderTimeMs: percentile(renderTimes, 99),463 fps: totalFrames > 0 ? Math.round(totalFrames / 10) : 0,464 };465}466467function parseFrameTimings(output: string): number[] {468 const lines = output.split('\\n');469 const timings: number[] = [];470 let inHistogram = false;471472 for (const line of lines) {473 if (line.includes('HISTOGRAM')) inHistogram = true;474 if (inHistogram && line.match(/^\\d/)) {475 const parts = line.trim().split(/\\s+/);476 if (parts.length >= 2) {477 timings.push(parseFloat(parts[0]));478 }479 }480 }481482 return timings;483}484485function percentile(values: number[], p: number): number {486 if (values.length === 0) return 0;487 const index = Math.ceil(values.length * (p / 100)) - 1;488 return values[Math.max(0, index)];489}490491async function execAdb(command: string): Promise<string> {492 const { execSync } = await import('child_process');493 return execSync(\`adb \${command}\`, { encoding: 'utf-8' });494}495async function navigateToScreen(screen: string): Promise<void> {}496function sleep(ms: number): Promise<void> { return new Promise((r) => setTimeout(r, ms)); }497```498499## Battery Consumption Testing500501```typescript502// android/battery/background-drain.test.ts503import { describe, it, expect } from 'vitest';504505describe('Battery Consumption', () => {506 const APP_PACKAGE = 'com.example.app';507508 it('should not drain more than 2% battery in 30 minutes of background', async () => {509 const initialBattery = await getBatteryLevel();510511 // Launch app and send to background512 await execAdb(\`shell am start -n \${APP_PACKAGE}/.MainActivity\`);513 await sleep(5000);514 await execAdb('shell input keyevent KEYCODE_HOME'); // Send to background515516 // Wait 30 minutes (or simulated time)517 await sleep(30 * 60 * 1000);518519 const finalBattery = await getBatteryLevel();520 const drain = initialBattery - finalBattery;521522 console.log(\`Battery drain: \${drain}% over 30 minutes\`);523 expect(drain).toBeLessThanOrEqual(2);524 });525526 it('should release wake locks when backgrounded', async () => {527 await execAdb(\`shell am start -n \${APP_PACKAGE}/.MainActivity\`);528 await sleep(5000);529 await execAdb('shell input keyevent KEYCODE_HOME');530 await sleep(10000);531532 const wakeLocks = await getAppWakeLocks(APP_PACKAGE);533 expect(wakeLocks).toBe(0);534 });535});536537async function getBatteryLevel(): Promise<number> {538 const output = await execAdb('shell dumpsys battery');539 const match = output.match(/level: (\\d+)/);540 return match ? parseInt(match[1], 10) : 0;541}542543async function getAppWakeLocks(packageName: string): Promise<number> {544 const output = await execAdb(\`shell dumpsys power | grep \${packageName}\`);545 return (output.match(/PARTIAL_WAKE_LOCK/g) || []).length;546}547548async function execAdb(command: string): Promise<string> {549 const { execSync } = await import('child_process');550 return execSync(\`adb \${command}\`, { encoding: 'utf-8' });551}552function sleep(ms: number): Promise<void> { return new Promise((r) => setTimeout(r, ms)); }553```554555## App Size Monitoring556557```typescript558// monitoring/app-size.ts559export interface AppSizeReport {560 totalSizeMB: number;561 downloadSizeMB: number;562 installSizeMB: number;563 components: Array<{564 name: string;565 sizeMB: number;566 percentage: number;567 }>;568 thresholdStatus: 'pass' | 'warning' | 'fail';569}570571export function analyzeApkSize(apkPath: string): AppSizeReport {572 // Analyze APK/AAB components573 return {574 totalSizeMB: 0,575 downloadSizeMB: 0,576 installSizeMB: 0,577 components: [],578 thresholdStatus: 'pass',579 };580}581582export const APP_SIZE_THRESHOLDS = {583 totalMB: { warning: 50, critical: 100 },584 downloadMB: { warning: 30, critical: 60 },585 dexFilesMB: { warning: 10, critical: 20 },586 nativeLibsMB: { warning: 15, critical: 30 },587 resourcesMB: { warning: 20, critical: 40 },588};589```590591## Best Practices5925931. **Test on real devices with representative hardware** -- Low-end and mid-range devices represent the majority of users. Do not only test on flagship phones.5942. **Measure cold and warm start separately** -- Users experience both scenarios. Cold start matters for first impressions; warm start matters for daily usage.5953. **Run performance tests multiple times** -- A single measurement is noisy. Run at least 10 iterations and report median and p95 values.5964. **Test under realistic network conditions** -- Use network throttling to simulate 3G, 4G, and lossy WiFi connections.5975. **Monitor memory across the entire user session** -- Brief memory spikes are acceptable. Continuous growth indicates leaks.5986. **Establish baselines and track regressions** -- Store performance baselines per release and fail tests when regressions exceed thresholds.5997. **Test with realistic data volumes** -- Empty lists and single items do not stress the app. Use hundreds of items with images and complex layouts.6008. **Include battery impact in performance criteria** -- An app that drains 10% battery per hour will get uninstalled regardless of feature quality.6019. **Automate performance tests in CI** -- Run performance tests on every release branch, not just manually before launch.60210. **Profile before optimizing** -- Use Android Profiler and Xcode Instruments to identify actual bottlenecks instead of guessing.603604## Anti-Patterns6056061. **Only testing on emulators** -- Emulator performance does not represent real device behavior. GPU rendering, memory management, and CPU throttling differ significantly.6072. **Measuring performance once** -- Single measurements are unreliable due to JIT compilation, background processes, and thermal throttling. Always aggregate multiple runs.6083. **Ignoring low-end devices** -- Most users do not have flagship phones. Test on devices with 2-3GB RAM and mid-range processors.6094. **Not testing offline scenarios** -- Users frequently lose connectivity. Apps that crash or hang without network are unusable.6105. **Skipping scroll performance testing** -- Janky scrolling is the most user-visible performance issue. Always measure frame rates during scroll.6116. **Testing only on WiFi** -- WiFi performance masks network-dependent bottlenecks. Always include 3G and 4G testing.6127. **Not monitoring memory during long sessions** -- Memory leaks may not appear in 30-second tests. Simulate 5-10 minute user sessions.6138. **Ignoring app size** -- Large APK/IPA files increase download time, storage usage, and initial launch time. Monitor and set size budgets.6149. **Not testing background behavior** -- Apps that consume CPU and network in the background drain battery and may be killed by the OS.61510. **Comparing performance across different device models** -- Always compare same-device measurements across versions, not different devices in the same run.