Skip to content

Performance

A PAM Native app keeps its PHP runtime alive, reconciles the interface in Rust, and renders real Android Views and UIKit controls. Scrolling, animation, text editing, image decoding, and media playback run natively without calling PHP on every frame. Most of the time, a slow or battery-hungry app is caused by application code: lists that mount every row, images that load full-size originals, or timers and requests that keep running on a screen nobody is looking at.

This page covers the rules that keep an app lean and how to check them on a real device. The rules are simple:

  • Render only what is visible. Use windowed lists and grids for collections.
  • Size every image and video for its view. Never decode a 4000 px original for a 64 pt avatar.
  • Stop work that cannot be seen. Timers, polling, players, and subscriptions pause when the screen is covered or the app goes to the background, and end when the component unmounts.
  • Keep per-frame work native. Animate with keyframes or worklets, not with PHP timers.
  • Measure on a device, with a release-optimized build, before you ship.

Never build a long collection with a Column and a foreach. Every row would be built, laid out, and mounted, even the ones thousands of points below the screen. Use the recycled list components instead:

Component Use it for
FlatList Plain text rows with a fixed row height.
VirtualizedList Rich or mixed rows (cards, media, rows with components).
VirtualGrid Multi-column cells with the same recycled contract.
SectionList Sectioned text rows.

VirtualizedList::of() is the data-driven form, similar to React Native’s data + renderItem + keyExtractor. The row closure runs only for rows inside the window (plus a margin), never for the whole collection up front:

src/Screens/FeedScreen.php
use Pam\Native\UI\VirtualizedList;
$list = VirtualizedList::of(
$this->posts,
fn (array $post, int $index) => PostRow::make($post),
key: fn (array $post) => $post['id'],
)
->estimatedRowHeight(320)
->windowSize(5)
->prefetch(4)
->onEndReached(fn () => $this->loadNextPage());
  • Stable keys. Keys default to the item’s key or id, then its index. Pass key: when neither exists, and never use the index for data that can be reordered or prepended.
  • windowSize($size) mounts the rows within ($size - 1) / 2 screens above and below the visible ones. Rows outside the window become placeholders with their last measured height, and their components unmount. Small values such as 5 suit tall media rows. Without windowSize, vertical lists of more than 96 rows are windowed automatically.
  • estimatedRowHeight() is the placeholder height before a row was ever shown. An explicit cell height always wins, so give media rows a real height.
  • prefetch() is clamped to 1–32 rows.

See Scroll and lists for every list option, pull-to-refresh, and scroll restoration.

The native image pipeline deduplicates requests, decodes off the UI thread, downsamples to a target size, and keeps bounded memory and disk caches. Give it the information it needs:

src/Components/PostRow.php
use Pam\Native\ImageFit;
use Pam\Native\MediaCachePolicy;
use Pam\Native\MediaPriority;
use Pam\Native\Style;
use Pam\Native\UI\Image;
$thumbnail = Image::make($post['imageUrl'])
->fit(ImageFit::Cover)
->resize(720, 405)
->sourceSet("{$post['imageUrl']} 1x, {$post['image2xUrl']} 2x")
->cache(MediaCachePolicy::StaleWhileRevalidate)
->cacheKey("post:{$post['id']}:v1")
->priority(MediaPriority::Visible)
->style(new Style(widthPercent: 100, height: 203));
  • resize($width, $height) decodes at the target size instead of the source size. This is the biggest memory win for photos and avatars.
  • Ask your server for the right size. resize() saves memory; only a smaller URL saves network and disk. Use sourceSet() for density variants.
  • A fixed height (or aspectRatio) keeps rows from jumping as images load.
  • priority() tells the pipeline which requests matter: Visible for on-screen content, Prefetch or Background for warming the cache.
  • Animated GIF/WebP belongs inside a VirtualizedList so only visible rows animate. Prefer animated WebP, which is usually smaller.

Cache policies, offline pinning, and cache usage reporting are covered in Images and cache.

MediaPlayer already releases resources you cannot see:

  • A player whose route is covered by a full-screen route, or whose tab is inactive, releases its decoder and recreates it at the same position when the route is visible again. Call keepAliveWhenCovered() only for audio that must continue under another screen.
  • The host pauses active media with the application lifecycle and only resumes what was playing.
  • On Android, a playing player keeps the screen on and releases that hold as soon as it pauses, ends, fails, or is hidden.

For feeds and vertical pagers, let the list decide which player runs:

src/Components/ClipRow.php
use Pam\Native\MediaType;
use Pam\Native\UI\MediaPlayer;
$player = MediaPlayer::make($clip['url'], MediaType::Video)
->thumbnail($clip['posterUrl'])
->muted()
->loop()
->autoPlayWhenVisible(0.6, group: 'feed')
// Release the decoder for cells far from the current page.
->idleSurface(!$isNearCurrentPage);
  • autoPlayWhenVisible($fraction, $group) plays only while the given fraction of the player is visible; players in the same group inside one list play one at a time. This is implemented by the Android renderer; on other renderers keep your own visibility gate.
  • idleSurface() releases the player, decoder, and network work while keeping the view and its poster mounted, so a neighbouring cell can play again without building a new video view.
  • downloadWhilePlaying() reads the file twice (stream and cache copy). Use it only when caching the whole file is worth it.

See Video and audio.

Anything that repeats (polling, countdowns, refresh loops, sensor or socket listeners) must stop when its screen is covered, when the app goes to the background, and when the component unmounts. PAM gives you hooks for each of these, and most of them clean up automatically.

$this->timers() returns timers owned by the component. They are cancelled on unmount, and by default they suspend in the background and re-arm when the app returns:

src/Components/Countdown.php
use Pam\Native\Attributes\State;
use Pam\Native\Component;
use Pam\Native\System\TimerBackgroundPolicy;
final class Countdown extends Component
{
#[State]
public int $seconds = 60;
public function setup(): void
{
$this->timers()->every(1_000, function ($timer): void {
if (--$this->seconds <= 0) {
$timer->cancel();
}
});
// A one-off timeout that should never fire after the app was backgrounded.
$this->timers()->timeout(
30_000,
fn () => $this->expire(),
background: TimerBackgroundPolicy::Cancel,
);
}
private function expire(): void
{
$this->seconds = 0;
}
}
TimerBackgroundPolicy Behavior in the background
Suspend (default) Stops the native timer and re-arms it on return. A timeout keeps its remaining delay; an interval restarts a full period.
Cancel Cancels the timer for good.
Continue Keeps running. Use it only for work that must finish in the background.

Intervals must be at least 16 ms. $this->timers() also provides debounce() and throttle(), which are released on unmount as well. Pam\Native\System\Timers remains available for work that is not tied to a component, but you must cancel those timers yourself.

A screen stays mounted while another screen is pushed on top of it, and tabs stay mounted while they are inactive. Use onFocus() and onBlur() inside setup() to run work only while the screen is visible:

src/Screens/InboxScreen.php
<?php
declare(strict_types=1);
namespace App\Screens;
use Pam\Native\Attributes\State;
use Pam\Native\Component;
use Pam\Native\Http\Http;
use Pam\Native\Http\HttpResponse;
use Pam\Native\Renderable;
use Pam\Native\System\ComponentTimer;
use Pam\Native\UI\Screen;
use Pam\Native\UI\Text;
use Pam\Native\UI\VirtualizedList;
use function Pam\Native\onBlur;
use function Pam\Native\onFocus;
final class InboxScreen extends Component
{
#[State]
public array $messages = [];
private ?ComponentTimer $poll = null;
public function setup(): void
{
onFocus(function (): void {
$this->refresh();
$this->poll = $this->timers()->every(30_000, fn () => $this->refresh());
});
onBlur(function (): void {
$this->poll?->cancel();
});
}
private function refresh(): void
{
Http::get('https://api.example.com/messages', function (HttpResponse $response): void {
if ($response->successful()) {
$this->messages = json_decode($response->body, true)['data'] ?? [];
}
});
}
public function render(): Renderable
{
return Screen::make(
VirtualizedList::of(
$this->messages,
fn (array $message) => Text::make($message['subject']),
)->estimatedRowHeight(56),
);
}
}

onFocus() runs each time the screen becomes visible (after its first mount), and onBlur() runs each time it is covered or left, and on unmount while focused. A component that is not under a route counts as focused while it is mounted. Classes that prefer methods can implement Pam\Native\Navigation\NavigationLifecycleAware (with the InteractsWithNavigationLifecycle trait) and override navigationFocused() and navigationBlurred().

Every component receives paused() when the app leaves the foreground and resumed() when it returns. Use them to flush drafts or stop work that is not a component timer:

src/Components/Editor.php
public function paused(): void
{
$this->autosave->flush();
}

For app-wide work, subscribe to state changes and keep the subscription owned by a component so it is released on unmount:

src/Components/LiveStatus.php
use Pam\Native\App;
use Pam\Native\AppState;
use Pam\Native\Events\Subscription;
public function setup(): void
{
$id = App::onStateChange(function (AppState $state): void {
$state === AppState::Active ? $this->connect() : $this->disconnect();
});
$this->own(Subscription::from(fn () => App::offStateChange($id)));
}

AppState::Inactive means system UI (a permission prompt, a picker, a share sheet) is covering the still-visible app; components also receive inactive() and activated() for that case.

When the system runs low on memory, the host reports it. Release what you can rebuild:

index.php
use Pam\Native\App;
use Pam\Native\Cache\BoundedStore;
use Pam\Native\MemoryPressure;
$profiles = new BoundedStore('profiles', maxItems: 200, maxBytes: 512 * 1024);
App::onMemoryPressure(function (MemoryPressure $level) use ($profiles): void {
$profiles->trim($level === MemoryPressure::Critical ? 0.0 : 0.5);
});

BoundedStore evicts the least recently used entries by count and by size, so in-memory caches never grow without limit. Native image and media caches are bounded by the runtime; set maxCacheSize() on images and players to lower those limits for a single source.

PHP never runs per frame unless you make it. Two common mistakes bring it back: driving an animation from a timer, and sending scroll or gesture positions to PHP to move views.

Use declarative keyframes, which run on the platform frame clock:

src/Components/Toast.php
use Pam\Native\AnimationEasing;
use Pam\Native\AnimationFillMode;
use Pam\Native\AnimationKeyframe;
use Pam\Native\UI\Animated;
$toast = Animated::make(
$content,
[
new AnimationKeyframe(0, opacity: 0, translationY: 16),
new AnimationKeyframe(1, opacity: 1, translationY: 0),
],
durationMs: 220,
easing: AnimationEasing::EaseOut,
)->fillMode(AnimationFillMode::Forwards);

For values that follow a gesture or a scroll offset, use worklets: bounded numeric programs that run on ValueAnimator (Android) and CADisplayLink (iOS) without re-entering PHP between frames. See Platform runtime and Interaction and motion.

The runtime records which state each component reads and re-renders only the components that depend on what changed. A component that is dirty only because of a descendant does not run its own template again; it re-renders only the path to that descendant. You get the most out of this by:

  • Keeping fast-changing state in small components. Typing in a composer component renders the composer, not the whole screen around it.
  • Keeping render() pure. No I/O, no json_decode() of large payloads, no sorting of big arrays. Do that work once, when the data arrives.
  • Using stable keys in lists and p-for loops, so rows keep their identity and native views.
  • Returning false from shouldUpdate() for components whose output does not depend on a prop change.

See State and lifecycle and Component runtime.

Everything in your project directory and Composer vendor directory ends up in the app bundle unless it is excluded. A smaller bundle installs faster, extracts faster on first launch, and uses less storage:

  • Install only the plugins you use. Optional features (camera, maps, payments, Bluetooth, and so on) live in separate pam-native-* plugins. Each one you add brings native code, dependencies, and often permissions. Remove what you no longer use with pam composer remove.

  • Exclude files that do not run on the device with a .pamignore file in the project root. It is an exact list of project-relative files and directories (no wildcards or negation):

    .pamignore
    docs/
    tests/
    design/
    phpunit.xml

    Directories and files whose names start with a dot, and node_modules, target, dist, and build directories, are always excluded.

  • Package release builds without development dependencies, for example by running pam composer install --no-dev before pam package, and restoring them afterwards.

The staged application is limited to 10,000 files, 8 MiB per file, and 128 MiB in total.

Debug builds include instrumentation and run unoptimized code. Measure performance with a release-optimized build on a physical device, ideally a mid-range one.

During pam dev, toggle the on-device overlay from another terminal:

Terminal window
pam devtools

It shows the smoothed frame rate, decode, mount, and commit times, rendered nodes, mutation batches, patch versus full commits, and native heap. Use it to find an expensive interaction, then confirm the fix with the tools below. See DevTools.

Terminal window
# Build an R8-optimized, non-debuggable APK signed with the debug key
pam build --benchmark
# Or build, install, and launch it on the connected device
pam run --release

The APK is written to dist/<name>-<version>-android-benchmark.apk. It needs no release keystore, so you can install it next to your debug build when android.benchmarkApplicationIdSuffix is set in pam-native.json.

With the release-optimized build running, use the standard Android tools. Replace com.example.acme with your applicationId:

Terminal window
# Frame times and janky frames since the last reset
adb shell dumpsys gfxinfo com.example.acme reset
# ...use the screen you are measuring for 10-20 seconds...
adb shell dumpsys gfxinfo com.example.acme
# Memory: total PSS, Java heap, native heap, graphics
adb shell dumpsys meminfo com.example.acme
# CPU use while the screen is idle (should be close to zero)
adb shell top -n 1 | grep com.example.acme

Debug builds install as <applicationId>.debug unless you set android.debugApplicationIdSuffix or use Firebase Messaging in debug.

Check these on every screen you ship:

  • Idle CPU is near zero when nothing moves. If not, something is polling or animating while hidden.
  • Memory returns to its previous level after you open and close a heavy screen a few times. Growth on every visit is a leak.
  • Janky frames stay low while you scroll the longest list at full speed.
  • Background: send the app to the background and check that CPU, network, and audio stop unless a feature needs them.
Terminal window
pam benchmark
pam profile

pam benchmark runs the Android Macrobenchmark suite on the connected device. It installs a separate, minified benchmark target with its instrumentation APK, so it never measures the .debug process you may have open. pam profile generates an Android Baseline Profile, which lets ART compile your startup and critical paths ahead of time.

For runtime evidence, pam diagnostics captures a redacted JSON snapshot from the running debug app: aggregate runtime metrics and a bounded timeline, without your app’s messages or labels.

Before you ship a screen:

  • Collections use FlatList, VirtualizedList, VirtualGrid, or SectionList with stable keys.
  • Every remote image has a target size (resize() or a sized URL) and a fixed height or aspect ratio.
  • Timers come from $this->timers(); polling starts in onFocus() and stops in onBlur().
  • Listeners and subscriptions are owned ($this->own()) or stopped in unmount().
  • Players use autoPlayWhenVisible() or idleSurface() in lists.
  • Animations use Animated keyframes or worklets, not PHP timers.
  • Idle CPU is near zero and memory is stable on a release-optimized build.
  • Content never sits under the status bar, notch, or navigation bar; see Safe areas.