Time-space domain finite-difference modeling has always had the problem of spatial and temporal dispersion. High-order finite-difference methods are commonly used to suppress spatial dispersion. Recently developed time-dispersion transforms can effectively eliminate temporal dispersion from seismograms produced by the conventional modeling of high-order spatial and second-order temporal finite differences. To improve the efficiency of the conventional modeling, I have developed optimal variable-length spatial finite differences to efficiently compute spatial derivatives involved in acoustic and elastic wave equations. First, considering that temporal dispersion can be removed, I prove that minimizing the relative error of the phase velocity can be approximately implemented by minimizing that of the spatial dispersion. Considering that the latter minimization depends on the wavelength that is dependent on the velocity, in this sense, this minimization is indirectly related to the velocity, and thus leads to variation of the spatial finite-difference operator with velocity for a heterogeneous model. Second, I use the Remez exchange algorithm to obtain finite-difference coefficients with the lowest spatial dispersion error over the largest possible wavenumber range. Then, dispersion analysis indicates the validity of the approximation and the algorithm. Finally, I use modeling examples to determine that the optimal variable-length spatial finite difference can greatly increase the modeling efficiency, compared to the conventional fixed-length one. Stability analysis and modeling experiments also indicate that the variable-length finite difference can adopt a larger time step to perform stable modeling than the fixed-length one for inhomogeneous models.