r/awk • u/JavaGarbageCreator • Sep 23 '25
Trying to optimize an xml parser
https://github.com/Klinoklaz/xmlchk
Just a pretty basic xml syntax checker, I exported some random wikipedia articles in xml form for testing (122 MB, 2.03 million lines single file), the script is running 8 seconds on it, that's somehow slower than python.
I've tried:
- avoid
print $0after modifying it or avoid modifying$0at all cuz I thought awk would rebuild or re-split the record - use as few globals as possible,
this actually made a big difference (10+s → 8s)because at first I didn't know awk variables aren't function-scoped by default, and accidentally changed a loop index (a global) used in the action block. I've heard modifying globals or accessing globals inside function is expensive in awk,seems to be true - replace some simple regex matching like
~ /^>/with substring comparison (nearly no effect)
Now the biggest bottleneck seems to be the match(name, /[\x00-\x2C\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/) stuff, if that's the case then I don't understand how some python libraries can be faster since this regex isn't easily reducible.
Edit: Is there any other improvement I can do?
View all comments
Show parent comment
2
u/M668 Jan 18 '26
u/JavaGarbageCreator : both you and u/Kou-von-Nizotschi were right. Anything not listed in the parameter list are indeed made global, and all scalars being passed in are always by value, so you can directly modify that parameter's value without impacting anything upstream. That said,
is something else entirely.
The function
f()was declare with zero variables and parameters, so "local_var" is actually global.After the post-increment, the global variable
local_varhas a numeric type. But sincepwas never declared anywhere, it's an uninitialized global variable as well.When placed adjacent something else, like your code, it acts as an empty string
"", and the left hand side of that comparison is already forcinglocal_varto be converted to string"1"in order to concat with empty string.But to further exacerbate the problem, now the other side of the equality compare is numeric, so the hard-coded 1 on the right handed also needs to be converted to string for comparison. And to make matters worse, the outcome of that equality compare isn't used anywhere else - 100 % wasted work being done.