Batch Performance Optimization

Introduction

Batch scripts can get slow when dealing with loops, file operations, variables, or repeated commands. This tutorial shows the real techniques used to squeeze maximum performance out of Windows Batch.

1. Disable Command Echoing

@echo off
    

Reduces console spam and speeds up loops slightly.

2. Use setlocal EnableDelayedExpansion Only When Needed

Delayed expansion is slower. Enable it only around logic that actually needs it.

setlocal EnableDelayedExpansion
REM your loop here
endlocal
    

3. Avoid Calling External Commands in Loops

These are slow: findstr, ping, powershell, wmic, where.

REM BAD:
for /l %%i in (1,1,1000) do ping localhost >nul

REM GOOD:
for /l %%i in (1,1,1000) do echo %%i >nul
    

4. Use Variables Instead of Repeated Commands

REM BAD:
for %%a in (*) do echo %cd%\%%a

REM GOOD:
set "cur=%cd%"
for %%a in (*) do echo %cur%\%%a
    

5. Avoid %random% in Tight Loops

It’s slow because CMD initializes more state per call.

6. Prefer if ... ( ) Over Multiple If Statements

if "%x%"=="1" (
  echo yes
) else (
  echo no
)
    

7. Pre-Calculate Strings Before Loops

set "prefix=[LOG]"
for %%a in (*) do echo %prefix% %%a
    

8. Use >nul 2>&1 Carefully

Redirecting output improves speed when a command is noisy.

9. Avoid for /f on Large Files

Batch is not designed for heavy file parsing.

Use PowerShell for anything large:

powershell -command "(gc log.txt).Length"
    

10. Avoid call Inside Loops

call is extremely slow. Inline logic instead.

REM BAD:
for %%i in (*) do call :process %%i

REM GOOD:
for %%i in (*) do (
  REM inline here
)
    

11. Use Built-In Commands Instead of External Tools

12. Disable Extensions When Not Needed

setlocal DisableExtensions
    

13. Use Short Paths for Faster Disk Access

set "tmp=%temp%"
cd /d "%tmp%"
    

14. Use exit /b 0 for Fast Returns

exit /b 0
    

15. Benchmarking Tip

set start=%time%
REM your code
echo Start: %start%
echo End:   %time%
    

Summary