I am benchmarking different approaches to RegEx and seeing something I really don't understand. I am specifically comparing using the -match
operator vs using the [regex]::Matches()
accelerator.
I started with
(Measure-Command {
foreach ($i in 1..10000) {
$path -match $testPattern
}
}).TotalSeconds
(Measure-Command {
foreach ($i in 1..10000) {
[regex]::Matches($path, $testPattern)
}
}).TotalSeconds
and -match
is always very slightly faster. But it's also not apples to apples because I need to assign the [Regex]
results to a variable to use it. So I added that
(Measure-Command {
foreach ($i in 1..10000) {
$path -match $testPattern
}
}).TotalSeconds
(Measure-Command {
foreach ($i in 1..10000) {
$test = [regex]::Matches($path, $testPattern)
}
}).TotalSeconds
And now [Regex]
is consistently slightly faster, which makes no sense because I added to the workload with the variable assignment. The performance difference is ignorable, 1/100th of a second when doing 10,000 matches, but I wonder what is going on under the hood to make [Regex]
faster when there is a variable assignment involved?
For what it's worth, without the variable assignment -match
is faster, .05 seconds vs .03 seconds. With variable assignment [Regex]
is faster by .03 seconds vs .02 seconds. So while it IS all negligible, adding the variable cuts [Regex]
processing time more than in half, which is a (relatively) huge delta.