GeneralSwitch statement performance

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
toberthanner
Posts: 2
Joined: Wed Mar 18, 2020 11:55 am

Switch statement performance

Post by toberthanner »

Hello,
I am facing performance issues when using switch statements with a large number of cases.
Defining a new command with an single argument (type int) and returning different content is working as expected BUT the compilation time is depending on the argument:
\tablexy{100} is fast but
\tablexy{6000} takes more than 30 seconds (i guess because it is at the very end of the switch statement)

Code: Select all

\newcommand{\tablexy}[1]{
\int_case:nnF{#1}{
{100}{some content}
{101}{some other content}
...
{6000}{again something different}
}
I also tried \IfStrEqCase with almost the same result.

I was first thinking of having a single command for each number like \tablexy100 ... \tablexy6000 but that is not possible because of the numbers in the command name.

The latex code is generated with c# from am Dictionary<int,string> (where the string contains latex code for tables) and i am open to other approaches. Just need to pick content out of this list based on the key (int).

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

User avatar
Ijon Tichy
Posts: 640
Joined: Mon Dec 24, 2018 10:12 am

Switch statement performance

Post by Ijon Tichy »

TeX itself does not provide a case-statement. So the \int_case:nnF results in a sequence of comparisons that stops if the true state is reached. So early true cases (= early true state) need more comparisons and more time than late true cases (= late true state).

With \@namedef and \@nameuse (\csname …\endcsname or the expl3 synonyms \cs:w…\cs:end: or \use:c) you can indeed define and use code sequences with Arabic numbers. Instead you could also use roman numbers instead of Arabic to be able to use them as macro names.

Another alternative would be to use luaTeX and implement such things using lua.
Sorry, but I can no longer participate here as the administrator is trampling on my wishes on one of his other platforms. :cry:
toberthanner
Posts: 2
Joined: Wed Mar 18, 2020 11:55 am

Switch statement performance

Post by toberthanner »

Thank you very much for pointing me in the right direction.

Code: Select all

\documentclass{article}

\makeatletter
% define each table
\@namedef{table1}#1{#1 content of table 1}%
\@namedef{table2}#1{#1 content of table 2}%

% helper function to access tables
\def\mytable#1#2{
  \@nameuse{table#1}{#2}%
}
\makeatother


\begin{document}
\mytable{1}{\section{table1}}
\mytable{2}{\section{table2}}
\end{document}
Post Reply