Skip to content

Performance problem: -cmatch prevents automatic caching of on-demand-compiled regexes #8941

Closed

Description

Note: This isn't a bug per se, but a performance issue.

Note that -creplace and switch -regex -casesensitive appear NOT to be affected.

Steps to reproduce

$strArray = , 'foo' * 1e5  # an array with N elements containing 'foo'
# Contrast the performance of -match vs. -cmatch
$scriptBlocks = 
 { foreach ($str in $strArray) { $null = $str -match  'f?(o)' } },
 { foreach ($str in $strArray) { $null = $str -cmatch 'f?(o)' } }

$scriptBlocks | % { (Measure-Command $_).TotalSeconds }

Expected behavior

Roughly the same execution time in both cases - -cmatch should actually be slightly faster.

Actual behavior

Sample result from my macOS 10.14.3 machine:

0.6651756
1.3135713

That is, -cmatch unexpectedly took about twice as long.

That this may be related to unexpectedly bypassing .NET's automatic caching of on-demand-compiled regexes is evidenced by the fact that if you force caching as follows, the problem goes away:

# Forces caching of the regex; running the above code again then performs as expected.
$null = switch -casesensitive -regex ($null) { 'f?(o)' { } }

Environment data

PowerShell Core v6.2.0-preview.4 on macOS 10.14.2
PowerShell Core v6.2.0-preview.4 on Ubuntu 18.04.1 LTS
PowerShell Core v6.2.0-preview.4 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.471)
Windows PowerShell v5.1.17134.407 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.471)

Activity

  1. added
    Issue-Question
    on Feb 21, 2019
  2. added
    WG-Engine-Performance
    and removed
    WG-Engine-Performance
    on Mar 23, 2019
  3. iSazonov commented on Sep 29, 2019

    @iSazonov
    Collaborator

    It's funny :-)

    We only use a Regex cache if IgnoreCase option presents.
    See internal static Regex NewRegex(string patternString, RegexOptions options)

    I guess it is because we want to keep the cache simple and fast. We could add second cache as simple solution. Dongbo Wang (@daxian-dbw) Thoughts? Make sense use ConcurrentDictionary?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-QuestionResolution-FixedWG-Engine-Performance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions