Increase LaTeX memory

LaTeX might run out of memory for some tasks. This article explains how to increase the working size.

LaTeX might run out of memory in certain scenarios. A possible scenario for such an exception is based on using TikZ or pgfplots (which requires TikZ). For instance if more than a dozen plots are contained within a single document, the following message (or similar) might be shown:

TeX capacity exceeded, sorry [main memory size=3000000].

Fortunately the main memory size can be changed. On Windows we can invoke the following commands to extend the memory size provided by the MikTeX distribution.

  1. Open a command Window or the PowerShell.
  2. At the shell, enter
    initexmf --edit-config-file=latex
  3. Add the following line
    main_memory=12000000
    to the file, save it and quit the editor.
  4. To rebuild the format, enter
    initexmf --dump=latex
  5. Repeat steps 2–4 with configuration files pdflatex and xelatex. Also you might want to repeat it with lualatex

Of course the bigger the number, the more plots you can store. However, just expanding the memory might not be the best solution. There is an even better way!

If we would compile each plot in its own document, we can get a speed up in successive LaTeX compilations due to caching. Also we would not need to enhance the memory for a single TeX instance, as one instance is certainly enough for a single plot. As we get an instance per plot, we will not run out of memory for sure.

In the preamble we only require the following additional instructions:

\usepgfplotslibrary{external} 
\tikzexternalize

Also we need to use the pdflatex command differently. We also need another parameter to explicitly allow such external calls.

This is called shell-escape and looks like the following:

pdflatex -shell-escape <filename>

This should now work flawlessly. Optionally one might be interested in specifying a path for placing the temporary (plot) files:

\tikzexternalize[prefix=cache/]

This will place all temporary files in the subdirectory called cache.

Of course there is one huge drawback for this method. Since the plot is externalized, the contents are also externalized. Unfortunately LaTeX does not support cross-document references, which is why things like citations won't work within externalized plots. Here we need to turn off the externalization.

The following snippet helps in managing such plots:

\tikzexternaldisable
% Code for the plot
\tikzexternalenable

So we only need to turn the feature off and on again. We could also just make an environment, which does that automatically, but for most things this should be sufficient.

Created . Last updated .

References

Sharing is caring!