In low-power gyrotrons with weak electron-wave interaction, there is a problem of determining the optimal length of the operating cavity, which is found as a result of a tradeoff between the enhancement of the electron efficiency and the increase in the Ohmic loss share with increasing cavity length. In fact, this is the problem of an optimal ratio between the diffraction and Ohmic Q-factors of the operating gyrotron mode, which determines the share of the radiated rf power lost in the cavity wall. In this paper, this problem is studied on the basis of a universal set of equations, which are appropriate for a wide class of electron oscillators with low efficiencies of the electron-wave interaction.