That seems rather slow for yours, and not very fast for an optimised one. It can speed up a lot from a cold start to a warm run, my tuned code can show 8 ms in powershell 7.4 after a few runs.
My hack-it-out code: https://pastebin.com/PDQhxDc9
Faster code: https://pastebin.com/6xwaVkwq
The hacky code uses slower techniques like:
- Get-Content which adds metadata to every line.
- @() arrays with += which copies the array in memory to a new one-larger memory location for every addition.
- Pipeline overhead e.g. ForEach-Object and Measure-Object.
- Filtering the whole second column for each number in the first column, repeated wasted work.
and it's still in the region of your ChatGPT one.
The faster one addresses these with:
- ReadAllLines() .NET method to get plain strings.
- [system.collections.generic.list[int]]::new() which don't box integers and can grow more quickly.
- plain adding numbers into sum variables.
- Building a hashtable [system.collections.generic.dictionary[int, int]]::new() to count each number in the second column.
- Swapping -split for string split() which may have a tiny bit less overhead.
- no pipelines.
The code isn't completely different, it's the same blocks doing the same things, leaning more on .NET lower levels, and years of experience of the basic PowerShell performance hits.