Performance & Optimization of Batch Files
Posted: 29 May 2020 17:18
Hi y'all. I wanted to know, is there a centralized list of knowledge to optimize performance in batch files? Readability and maintainability is not a concern - I'll be using these tips and trips to auto-generate some fast batch code at some point in the future. Currently, I've assembled this list of knowledge (and I'll be updating the OP to include new information shared):
- Use parenthesis to have CMD read your code into memory before it executes (needs source)
WARNING: this trick induces early expansion of % variables. Use SETLOCAL ENABLEDELAYEDEXPANSION and !s to prevent this.
- Perform multiple SET operations at once (needs source)
- Perform manual loop unrolling (needs source)
- Name variables closer to the start of the alphabet (A) if they are static (not changed often), else name them closer to the end of the alphabet (ZZZZ) if they are dynamic (updated frequently) source
- Try to avoid GOTOs, CALLs, FOR, and other forms of control flow indirection. Instead of GOTOs or CALLs, use macros source
Anyways, if you have any more performance tips & tricks, please do share!
- Use parenthesis to have CMD read your code into memory before it executes (needs source)
WARNING: this trick induces early expansion of % variables. Use SETLOCAL ENABLEDELAYEDEXPANSION and !s to prevent this.
Code: Select all
(
echo Hello, World!
set /p "name=Hello> "
echo Hello, !name!
)
Code: Select all
set /a "first=0, second=1"
Code: Select all
for /L %%A in (1,1,10) do echo %%A
::turns into
echo 1
echo 2
echo 3
echo 4
echo 5
echo 6
echo 7
echo 8
echo 9
echo 10
Code: Select all
set A="static"
set Z="dynamic"
echo %Z%
set Z="variable"
echo %Z%
Code: Select all
::Example linked at source for macros