Where can I learn optimizing cpp code

Include what you use

We use and but the code lacks the necessary includes:

Perform a single task well

Why do we perform the Gaussian blur? What if the input is already sufficiently blurred, or if it needs a bigger kernel?

If we make the caller responsible for this preparation step, we give it more control, and we can focus on a single responsibility in this function.

Fix the memory leak

This allocation is never released:

In fact, this entire (global) array seems only to be assigned to, and never used, so we could remove it entirely.

Simplified indexing

It might be easier to use throughout, and add rows or columns directly with ± and ±:

Use the standard library

There's no need to (badly) re-write for the computation of (also, drop the - that's always false).

Saturate, don't overflow

The value could conceivably be larger than the range of , or of (depending on the relative sizes of the target's integer types) - in such cases, we should the value to the possible range, rather than suffering Undefined Behaviour.


Prefer standard spelling: gradient, not .


answered Jan 9 '19 at 14:22

Toby SpeightToby Speight

36.3k88 gold badges4848 silver badges147147 bronze badges