← Back to posts Cover image for Flutter Performance: When to Use C++ (and When Not To) for Critical Logic

Flutter Performance: When to Use C++ (and When Not To) for Critical Logic

· 5 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

When building Flutter apps, we occasionally hit a performance wall. A complex animation stutters, a large dataset takes too long to process, or a real-time audio filter can’t keep up. Your first thought might be: “Should I rewrite this in C++?” It’s a powerful tool, but it adds significant complexity. Let’s break down when this nuclear option is justified, and when you can achieve your goals with pure Dart.

The FFI Reality: It’s Not a Free Lunch

Flutter’s Foreign Function Interface (FFI) lets you call C, C++, Rust, or other native code directly. It’s incredibly powerful, but it comes with overhead. Every FFI call involves a context switch between the Dart VM and native memory. For a single, heavy computation, this is negligible. But if you’re calling a native function thousands of times per second in a tight loop, that overhead can erase any performance gains and even make things slower.

When FFI overhead dominates:

// Hypothetical BAD use case: Calling C++ for a trivial, repeated task
int sumListFfi(List<int> data) {
  int result = 0;
  for (var value in data) {
    // Each iteration incurs FFI call overhead!
    result = nativeAdd(result, value); // Assume `nativeAdd` is a C++ function
  }
  return result;
}

The native add function is lightning fast, but the FFI marshalling for each element makes this approach far slower than a pure Dart loop.

When C++ Shines: The Justifiable Use Cases

So when does C++ make sense? It excels in scenarios where you can do a large amount of work per FFI call. You push a big batch of data into native memory, let C++ crunch it using optimized algorithms or hardware-specific instructions (like SIMD), and pull back a single result.

1. Heavy Mathematical/Simulation Kernels: Physics engines, complex financial modeling, or image/video processing (e.g., applying a convolution filter to a 4K image). 2. Leveraging Existing Native Libraries: You need a specific, battle-tested C library for audio encoding (like Opus) or advanced cryptography. 3. Platform-Specific Hardware Access: Low-latency audio processing or advanced GPU computing that isn’t yet exposed by a Flutter plugin.

Example: Image Grayscale Conversion A naive Dart pixel-by-pixel loop can be slow for a large image. A C++ function can process the entire image buffer in one call.

C++ side (simplified):

// native_image_processing.cpp
extern "C" {
    void convertToGrayscale(uint8_t* pixelData, int length) {
        // Process ALL pixels in a single, optimized native loop.
        for (int i = 0; i < length; i += 4) { // RGBA
            uint8_t gray = (uint8_t)(0.299 * pixelData[i] +
                                     0.587 * pixelData[i + 1] +
                                     0.114 * pixelData[i + 2]);
            pixelData[i] = pixelData[i+1] = pixelData[i+2] = gray;
        }
    }
}

Dart/Flutter side:

// image_provider.dart
import 'dart:ffi';
import 'dart:typed_data';
import 'package:image/image.dart' as img;

final DynamicLibrary nativeLib = Platform.isAndroid
    ? DynamicLibrary.open('libnative_image.so')
    : DynamicLibrary.process();

final _convertToGrayscaleNative = nativeLib.lookupFunction<
    Void Function(Pointer<Uint8>, Int32),
    void Function(Pointer<Uint8>, int)>('convertToGrayscale');

Uint8List convertToGrayscale(Uint8List imageBytes) {
  // Decode image
  final image = img.decodeImage(imageBytes)!;
  final rgbaBytes = image.getBytes(format: img.Format.rgba);

  // Allocate native memory and copy data ONCE.
  final nativeBuffer = malloc.allocate<Uint8>(rgbaBytes.length);
  nativeBuffer.asTypedList(rgbaBytes.length).setAll(0, rgbaBytes);

  // Single FFI call to process the entire image.
  _convertToGrayscaleNative(nativeBuffer, rgbaBytes.length);

  // Copy result back.
  final resultBytes = Uint8List.fromList(
      nativeBuffer.asTypedList(rgbaBytes.length));
  malloc.free(nativeBuffer);

  return resultBytes;
}

The key is the single FFI call for the entire operation.

The Dart-First Optimization Checklist

Before you even consider C++, exhaust these pure-Dart strategies:

  1. Profile, Don’t Assume: Use the Dart DevTools CPU Profiler and Flutter Performance overlay. Is your bottleneck really in your business logic, or is it in UI layout/rendering?
  2. Use Efficient Data Structures: Are you using List for lookups by key? Switch to a Map or Set. For queues, consider Queue.
  3. Leverage Isolates for Parallelism: Dart is single-threaded. If your logic is CPU-bound, move it to an Isolate to avoid blocking the UI thread. This is often enough.
    // Perform heavy parsing/computation in an Isolate
    Future<ProcessedResult> parseLargeData(String jsonString) async {
      return await compute(_heavyParseFunction, jsonString);
    }
    static ProcessedResult _heavyParseFunction(String json) {
      // Your complex logic here, runs on a separate thread.
    }
  4. Algorithmic Optimization: A better O(n log n) algorithm in Dart will almost always beat a poor O(n²) algorithm in C++ for sufficiently large n.
  5. Use Float64List or Int32List for Numerics: For heavy numeric work, these typed lists are much faster than regular List<dynamic>.

Common Mistakes & Final Verdict

  • Mistake 1: Rewriting trivial or non-measured bottlenecks in C++.
  • Mistake 2: Creating a chatty interface with many small FFI calls.
  • Mistake 3: Neglecting the development cost: you now have two toolchains (Dart/Flutter & C++), need to handle platform-specific builds, and have a harder-to-debug codebase.

When to Use C++: When you have a proven, isolated performance bottleneck involving heavy computation on large data batches, and Dart/Isolate optimization has hit its limit. The performance gain must outweigh the long-term maintenance burden.

When Not To: For general app logic, UI state management, network calls, or anywhere the FFI call overhead would be a significant fraction of the work. Most Flutter apps will never need it.

Start with Dart, profile relentlessly, optimize your algorithms, and use Isolates. Reach for C++ only when you have clear, quantitative evidence that it’s the only way to meet your performance requirements.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.