The increasing penetration of new renewable sources of electrical energy reduces the overall mechanical inertia available in power grids. This raises a number of issues regarding grid stability over short to medium time scales. A number of approaches have been proposed to compensate for this inertia reduction by deploying substitution inertia in the form of synchronous condensers, flywheels or power-electronic-based synthetic inertia. These resources are limited and expensive; therefore, a key issue is to determine how to optimally place them in the power grid, for instance, to mitigate voltage angle and frequency disturbances following an abrupt power loss. Performance measures in the form of H 2 - norms have recently been introduced to evaluate the overall magnitude of such disturbances. However, despite the mathematical convenience of these measures, analytical results can only be obtained under rather unrealistic assumptions of a uniform damping-to-inertia ratio or a homogeneous distribution of the inertia and/or primary control. Here, we introduce and apply matrix perturbation theory to obtain analytical results for an optimal inertia and primary control placement in the case where both are heterogeneous. This powerful method allows us to construct two simple algorithms that independently optimize the geographical distribution of the inertia and primary control. The algorithms are then implemented for a numerical model of the synchronous transmission grid of continental Europe with different initial configurations. We find that an inertia redistribution has little effect on the grid performance but that the primary control should be redistributed on the slow modes of the network, where the intrinsic grid dynamic requires more time to damp frequency disturbances. For a budget-constraint optimization, we show that increasing the amount of primary control in the periphery of the grid, without changing the inertia distribution, achieves 90 % or more of the maximal possible optimization, already for relatively moderate budgets.