The amsxtra package provides the \accentedsymbol command which typesets the argument and stores the result. This can speed up LaTeX compilation significantly if lots of accents etc. are used frequently. The problem is that \accentedsymbol typesets only one size, so you need to have different macros for all math styles.
Question
How can I define a command similar to \accentedsymbol that works properly in all math display styles?
Comments
The solution probably involves using \mathchoice. Here is a minimal working example that implements a \mathchoice solution by hand. Is this the best solution? (Some issues about \mathchoice are discussed in the references below.) How can this be automated? Since the goal here is performace, is \mathchoice a good option? (The TeXbook warns that it is slow, but since I am only typesetting saved boxes, maybe this is fine. It seems to work well with intermediate sized problems I have tested.)
\documentclass{standalone}
\usepackage{amsxtra}
\accentedsymbol\vkbad{\vec{\mathbf{k}}}
\accentedsymbol\vkD{\displaystyle \vec{\mathbf{k}}}
\accentedsymbol\vkT{\textstyle \vec{\mathbf{k}}}
\accentedsymbol\vkS{\scriptstyle \vec{\mathbf{k}}}
\accentedsymbol\vkSS{\scriptscriptstyle \vec{\mathbf{k}}}
\newcommand{\vk}{\mathchoice{\vkD}{\vkT}{\vkS}{\vkSS}}
\begin{document}
This is bad: $\vkbad = x_{\vkbad}$. This is good: $\vk = x_{\vk}$.
\end{document}

\smallor\largecontext. – egreg May 02 '12 at 13:13