Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

WebGL Shader Performance Optimization on Mobile

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through practical steps to make your WebGL shaders run faster and smoother on mobile devices. Mobile GPUs have different constraints than desktop ones, so shaders that work fine on a PC can stutter or drain battery on a phone. By the end, you'll know how to write shaders that respect those limits, reduce overdraw, and keep frame rates stable.

What You'll Need

  • A WebGL project you can edit (any framework or raw WebGL).
  • A mobile device or the mobile emulation mode in your browser's dev tools.
  • Browser developer tools with a performance profiler (Chrome DevTools or Safari Web Inspector).
  • Basic familiarity with GLSL (the shader language) and the WebGL API.

Step-by-Step

  1. Profile first, optimize second. Open your app on the mobile device and use the browser's performance panel to record a few seconds of interaction. Look for the "GPU" row or shader-related timings. Identify which draw calls or shaders take the most time. Don't guess—measure.
  2. Reduce shader complexity in the fragment shader. The fragment shader runs for every pixel on screen, so it's the biggest bottleneck. Count the number of arithmetic operations and texture fetches. Aim to keep it under 20-30 instructions for simple apps, and under 100 for complex ones. Remove anything that doesn't visibly improve quality.
  3. Use half precision where possible. In GLSL ES (the version used by WebGL), you can declare mediump float or lowp float for variables that don't need high precision, like colors, UV coordinates, and simple offsets. High precision (highp float) is slower on many mobile GPUs. Test each variable—if quality doesn't suffer, keep it at medium or low.
  4. Minimize texture fetches. Each texture sample costs memory bandwidth. Combine multiple textures into a single texture atlas or use a texture array if you need several images. Avoid sampling the same texture multiple times in one shader; reuse the value if possible. Also, use smaller textures—a 512x512 texture uses a quarter of the bandwidth of a 1024x1024 one.
  5. Avoid dynamic branching in fragment shaders. Mobile GPUs often execute both branches of an if statement, so branching can double your cost. Replace conditionals with mathematical tricks like mix(), step(), or smoothstep(). For example, instead of if (x > 0.5) color = a; else color = b;, use color = mix(a, b, step(0.5, x));.
  6. Use vertex shaders for heavy math. The vertex shader runs once per vertex, which is usually far fewer times than the fragment shader runs per pixel. Move calculations like lighting, normals transforms, and procedural animations to the vertex shader if they don't need per-pixel detail.
  7. Reduce overdraw. Overdraw happens when you draw pixels multiple times. Use depth testing (gl.enable(gl.DEPTH_TEST)) and make sure you clear the depth buffer each frame. Also, draw opaque objects first, then transparent ones. For transparent objects, consider using additive blending or reducing their size on screen.
  8. Batch draw calls. Each draw call has overhead. Combine multiple meshes into one buffer and draw them with a single call if they share the same shader and material. Use instancing (gl.drawArraysInstanced or ANGLE_instanced_arrays) for many similar objects like particles or trees.
  9. Use the simplest shader possible for each object. Don't use a PBR shader for a plain white cube. Create multiple shader variants and switch based on material properties. For example, a shader without shadows is faster than one with shadow mapping.
  10. Test on real devices. Emulators don't reflect real GPU performance. Test on at least one low-end and one mid-range Android phone and an iPhone. Use the device's built-in FPS overlay or a simple on-screen counter to measure actual frame rate.

Common Mistakes

  • Using highp everywhere. It's tempting to set everything to high precision, but it slows down mobile GPUs significantly. Only use highp for positions and normals in the vertex shader, and for depth calculations in the fragment shader.
  • Ignoring texture compression. Uncompressed textures use more bandwidth. Use compressed formats like ETC2 or ASTC (via extensions) when possible. They load faster and render faster.
  • Forgetting to disable unused features. If you don't need depth testing, blending, or stencil, turn them off. Each enabled feature adds per-pixel work.
  • Overusing discard in fragment shaders. The discard keyword breaks early-z optimization on many GPUs, causing slower rendering. Use alpha blending or adjust geometry instead.
  • Not checking for extension support. Features like instancing or texture compression may not be available on older devices. Always check with getExtension() and provide fallbacks.

Tips

  • Use the #ifdef preprocessor directives in GLSL to create shader variants without duplicating code.
  • Keep shader source strings short—shader compilation time is also part of performance, especially on mobile.
  • Consider using a lower resolution render target for post-processing effects, then upscale.
  • Use requestAnimationFrame properly and avoid blocking the main thread with heavy shader compilation. Compile shaders asynchronously or during loading screens.
  • Monitor the number of uniform updates—setting uniforms every frame adds CPU overhead. Batch them if possible.

Troubleshooting

Frame rate is still low after optimization. Re-profile to see if the bottleneck moved. It might now be in the CPU (draw calls, JavaScript) or in memory bandwidth. Use the performance panel to check for long tasks or high memory usage.

Shaders look different on mobile. Precision differences can cause banding or flickering. If you reduced precision too aggressively, raise it back for the affected variables. Also check that your textures have appropriate mipmaps and filtering settings.

Some devices show black screens or errors. This often means you're using a feature not supported on that GPU. Check the browser console for GLSL compilation errors. Simplify the shader or add fallbacks for unsupported extensions.

Profiling shows no GPU time but frame rate is low. The bottleneck might be the CPU, not the shader. Look at your JavaScript—are you doing heavy calculations per frame? Are you creating new objects? Optimize the CPU side as well.

Frequently Asked Questions

Why is my shader fast on desktop but slow on mobile?

Mobile GPUs have less memory bandwidth, fewer shader cores, and different architecture. They're optimized for low power, not raw speed. Instructions that are cheap on desktop (like highp math or branching) can be expensive on mobile.

What's the most important thing to optimize in a shader?

The fragment shader. It runs per pixel, so even a small reduction in instructions can have a huge impact. Focus on reducing texture fetches and arithmetic operations there.

Should I use lowp for all my variables?

No. Lowp has very limited range and precision, often only 8 bits. It's fine for colors and simple UVs, but not for positions, normals, or depth. Use mediump for most things and highp only where needed.

How do I check if my shader compiles correctly on mobile?

Open your app on the device and check the browser console for errors. Also, use gl.getShaderParameter(shader, gl.COMPILE_STATUS) in your code and log the info log if it fails. Test on multiple devices if possible.

Can I use WebGL 2 for better performance?

WebGL 2 offers features like uniform buffers, texture arrays, and more flexible vertex formats, which can improve performance. However, not all mobile browsers support it fully. Check compatibility and provide a WebGL 1 fallback.

Does reducing the canvas resolution help?

Yes, lowering the canvas resolution reduces the number of pixels the fragment shader processes. You can scale the canvas with CSS to maintain visual size. This is one of the easiest ways to boost performance, but it can make the image blurry, so find a balance.