Skip to content

Commit 510a24b

Browse files
committed
merged conflict: Performance improvement for most common usage
2 parents eac7d86 + ab0aea1 commit 510a24b

File tree

5 files changed

+562
-460
lines changed

5 files changed

+562
-460
lines changed

VerbalExpressions/RegexCache.cs

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
using System;
2+
using System.Text.RegularExpressions;
3+
4+
namespace CSharpVerbalExpressions
5+
{
6+
public sealed class RegexCache
7+
{
8+
private bool hasValue;
9+
private Key key;
10+
private Regex regex;
11+
12+
private class Key
13+
{
14+
public Key(string pattern, RegexOptions options)
15+
{
16+
this.Pattern = pattern;
17+
this.Options = options;
18+
}
19+
20+
public string Pattern { get; private set; }
21+
public RegexOptions Options { get; private set; }
22+
23+
public override bool Equals(object obj)
24+
{
25+
var key = obj as Key;
26+
return key != null &&
27+
key.Pattern == this.Pattern &&
28+
key.Options == this.Options;
29+
}
30+
31+
public override int GetHashCode()
32+
{
33+
return this.Pattern.GetHashCode() ^ this.Options.GetHashCode();
34+
}
35+
}
36+
37+
/// <summary>
38+
/// Gets the already cached value for a key, or calculates the value and stores it.
39+
/// </summary>
40+
/// <param name="pattern">The pattern used to create the regular expression.</param>
41+
/// <param name="options">The options for regex.</param>
42+
/// <returns>The calculated or cached value.</returns>
43+
public Regex Get(string pattern, RegexOptions options)
44+
{
45+
if (pattern == null) throw new ArgumentNullException("pattern");
46+
47+
lock (this)
48+
{
49+
var current = new Key(pattern, options);
50+
if (this.hasValue && current.Equals(this.key))
51+
{
52+
return this.regex;
53+
}
54+
55+
this.regex = new Regex(pattern, options);
56+
this.key = current;
57+
this.hasValue = true;
58+
return this.regex;
59+
}
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)