r/awk • • 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:

  1. avoid print $0 after modifying it or avoid modifying $0 at all cuz I thought awk would rebuild or re-split the record
  2. 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
  3. 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?

6 Upvotes

11 comments sorted by

View all comments

Show parent comment

1

u/JavaGarbageCreator Feb 28 '26 edited Feb 28 '26

I was thinking of sed at that time and misused the sed syntax. Tried to rewrite some xml parsing logic in sed, it was possible through heavy use of hold space but too much of a hassle, I had to give up

1

u/M668 Mar 08 '26

awk is a intentionally light weight but still full blown language. It doesn't require hold spaces to get things done. I totally agree that sed is a major hassle. i keep my usage of it to a minimal