# Benchmarking different RegEx implementations

**URL:** <https://forums.swift.org/t/benchmarking-different-regex-implementations/90008>\
**Category:** Using Swift\
**Tags:** benchmarks, regex\
**Created:** [October 11, 2026, 10:12pm UTC](https://forums.swift.org/t/benchmarking-different-regex-implementations/90008 "2026-10-11T22:12:42Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![LeoAvMo](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/leoavmo/32/45329_2.png) [@LeoAvMo](https://forums.swift.org/u/LeoAvMo)\
**Post date:** [October 11, 2026, 10:12pm UTC](https://forums.swift.org/t/benchmarking-different-regex-implementations/90008/1 "2026-10-11T22:12:42Z")

</div>

As part of my compilers class, the teacher told me that we will be coming across with _Regular Expressions_ (RegEx). Since I want to do the project in Swift, I tried experimenting today with the ways to do RegExs. After some investigation, I found 4 ways with a different purpose each: RegEx literals, RegEx builder, Dynamic Pattern, and NSRegularExpression.

I created a function for each one of them and measured the runtime for each one of them using the same 2 inputs and the same regular expression for email validation:

**^[a-zA-Z0-9.\_%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$**

- Correct email input: "[mymail@gmail.com](mailto:mymail@gmail.com)"
- Incorrect email input: "mymail@@gmail.com""

Here's the code for each function:

## **RegEx Literal**

```swift
func regExLiteral(numberOfTests: Int) -> [Double] {
    
    // Inputs
    let correctInput = "mymail@gmail.com"
    let invalidInput = "mymail@@gmail.com"
    
    // Time Outputs
    var correctInputTime: Double = 0.0
    var invalidInputTime: Double = 0.0
    
    // Regex literal
    let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    
    for _ in 1...numberOfTests {
        // Valid input
        let startTime1 = CFAbsoluteTimeGetCurrent()
        
        if let match = correctInput.firstMatch(of: regex) { }
        
        let diff1 = CFAbsoluteTimeGetCurrent() - startTime1
        
        correctInputTime += diff1
    }
    
    for _ in 1...numberOfTests {
        // Invalid input
        let startTime2 = CFAbsoluteTimeGetCurrent()
        
        if let match = invalidInput.firstMatch(of: regex) { } else { }
        
        let diff2 = CFAbsoluteTimeGetCurrent() - startTime2
        
        invalidInputTime += diff2
    }
    
    
    return [correctInputTime / Double(numberOfTests), invalidInputTime / Double(numberOfTests)]
}

```

## **RegEx Builder**

```swift
func regExBuilder(numberOfTests: Int) -> [Double] {
    
    // Inputs
    let correctInput = "mymail@gmail.com"
    let invalidInput = "mymail@@gmail.com"
    
    // Time Outputs
    var correctInputTime: Double = 0.0
    var invalidInputTime: Double = 0.0
    
    // RegEx Builder
    let regex = Regex {
        /^/
        OneOrMore {
            CharacterClass(
                .anyOf("._%+-"),
                ("a"..."z"),
                ("A"..."Z"),
                ("0"..."9")
            )
        }
        "@"
        OneOrMore {
            CharacterClass(
                .anyOf(".-"),
                ("a"..."z"),
                ("A"..."Z"),
                ("0"..."9")
            )
        }
        "."
        Repeat(2...) {
            CharacterClass(
                ("a"..."z"),
                ("A"..."Z")
            )
        }
        /$/
    }
    
    for _ in 1...numberOfTests {
        // Valid input
        let startTime1 = CFAbsoluteTimeGetCurrent()
        
        if let match = correctInput.firstMatch(of: regex) { }
        
        let diff1 = CFAbsoluteTimeGetCurrent() - startTime1
        
        correctInputTime += diff1
    }
    
    for _ in 1...numberOfTests {
        // Invalid input
        let startTime2 = CFAbsoluteTimeGetCurrent()
        
        if let match = invalidInput.firstMatch(of: regex) { } else { }
        
        let diff2 = CFAbsoluteTimeGetCurrent() - startTime2
        
        invalidInputTime += diff2
    }
    
    
    return [correctInputTime / Double(numberOfTests), invalidInputTime / Double(numberOfTests)]
}

```

## **Dynamic Pattern**

```swift
func dynamicPattern(numberOfTests: Int) throws -> [Double] {

    // Inputs
    let correctInput = "mymail@gmail.com"
    let invalidInput = "mymail@@gmail.com"

    // Time Outputs
    var correctInputTime: Double = 0.0
    var invalidInputTime: Double = 0.0

    // RegEx Pattern From String, compiled at runtime
    let pattern = #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"#
    let regex = try Regex(pattern)
    
    for _ in 1...numberOfTests {
        // Valid input
        let startTime1 = CFAbsoluteTimeGetCurrent()
        
        if let match = correctInput.firstMatch(of: regex) { }
        
        let diff1 = CFAbsoluteTimeGetCurrent() - startTime1
        
        correctInputTime += diff1
    }
    
    for _ in 1...numberOfTests {
        // Invalid input
        let startTime2 = CFAbsoluteTimeGetCurrent()
        
        if let match = invalidInput.firstMatch(of: regex) { } else { }
        
        let diff2 = CFAbsoluteTimeGetCurrent() - startTime2
        
        invalidInputTime += diff2
    }
    
    
    return [correctInputTime / Double(numberOfTests), invalidInputTime / Double(numberOfTests)]
}

```

## **NSRegularExpression**

```swift
func nsRegularExpression(numberOfTests: Int) throws -> [Double] {
    
    // Inputs
    let correctInput = "mymail@gmail.com"
    let invalidInput = "mymail@@gmail.com"
    
    // Time Outputs
    var correctInputTime: Double = 0.0
    var invalidInputTime: Double = 0.0
    
    // RegEx Pattern From String
    let regex = #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"#
    let nsRegex = try NSRegularExpression(pattern: regex)
    
    for _ in 1...numberOfTests {
        // Valid input
        let startTime1 = CFAbsoluteTimeGetCurrent()
        
        if let match = nsRegex.firstMatch(in: correctInput, range: NSRange(correctInput.startIndex..., in: correctInput)) { }
        
        let diff1 = CFAbsoluteTimeGetCurrent() - startTime1
        
        correctInputTime += diff1
    }
    
    for _ in 1...numberOfTests {
        // Invalid input
        let startTime2 = CFAbsoluteTimeGetCurrent()
        
        if let match = nsRegex.firstMatch(in: invalidInput, range: NSRange(invalidInput.startIndex..., in: invalidInput)) { } else { }
        
        let diff2 = CFAbsoluteTimeGetCurrent() - startTime2
        
        invalidInputTime += diff2
    }
    
    
    return [correctInputTime / Double(numberOfTests), invalidInputTime / Double(numberOfTests)]
}

```

# The results

I was surprised that NSRegularExpression was the fastest. I expected RegEx builder to perform better since it's a newer framework. However, the advantage of RegEx builder is its readability.

These were the results for for **1000** iterations:

```swift
Best average correct input time:
1° NSRegularExpression: 8.584856986999512e-06
2° Dynamic Pattern: 9.155392646789551e-06
3° RegEx Literal: 9.646296501159668e-06
4° RegEx Builder: 1.1594653129577637e-05

Best average incorrect input time:
1° NSRegularExpression: 8.304238319396973e-06
2° Dynamic Pattern: 8.513808250427246e-06
3° RegEx Literal: 8.91125202178955e-06
4° RegEx Builder: 9.9104642868042e-06

```

And these ones for **50000** iterations:

```swift
Best average correct input time:
1° NSRegularExpression: 8.425192832946778e-06
2° Dynamic Pattern: 8.737547397613526e-06
3° RegEx Literal: 8.877315521240235e-06
4° RegEx Builder: 1.1499965190887451e-05

Best average incorrect input time:
1° NSRegularExpression: 8.177592754364013e-06
2° RegEx Literal: 8.334076404571533e-06
3° Dynamic Pattern: 8.338320255279541e-06
4° RegEx Builder: 9.476649761199952e-06

```

## So… what are the results?

Yes, NSRegularExpression was the fastest, but it is checked at runtime (along with Dynamic Pattern), not ensuring type safety. RegEx Literals and RegEx builder do ensure type safety and are checked at compile time.

For the scope of my project, maybe i'll stick to RegEx Literals, mainly because it will let me build easily copy and paste RegExs in easily into online tools for testing RegExs, but for real projects, RegEx builder seems like a good option for readability.

If there's something I might be wrong about or might be overlooking, I look forward to hearing opinions!

---

<div class="post-metadata">

**Author:** ![AlexisQapa](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexisqapa/32/7159_2.png) [@AlexisQapa](https://forums.swift.org/u/AlexisQapa)\
**Post date:** [October 12, 2026, 10:57am UTC](https://forums.swift.org/t/benchmarking-different-regex-implementations/90008/2 "2026-10-12T10:57:14Z")

</div>

I don’t remember if the new APIs are expected to be always faster, there are some departures from other languages around utf8 so the behavior is coherent with swift string for example. Though I don’t expect this kind of difference, did you compile in release mode ? Static code being slower that dynamic one look like you compare debug code vs optimised one.

---

<div class="post-metadata">

**Author:** ![aviva](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/aviva/32/44327_2.png) [@aviva](https://forums.swift.org/u/aviva)\
**Post date:** [October 12, 2026, 9:27pm UTC](https://forums.swift.org/t/benchmarking-different-regex-implementations/90008/3 "2026-10-12T21:27:24Z")

</div>

No clue on the different in performance between these types, but benchmarking is hard, the variable `match` is completely unused in your code. How do you know the regex match was not entirely eliminated in some of your benchmarks? Using a [black hole](https://swiftpackageindex.com/ordo-one/benchmark/main/documentation/benchmark/benchmark/blackhole(_:)) style function or macro is a traditional solution to ensure the thing you want to benchmark isn't optimized out / in a way that defeats your benchmark.

Maybe these docs are helpful? [Benchmark Documentation – Swift Package Index](https://swiftpackageindex.com/ordo-one/benchmark/main/documentation/benchmark) They don't have as much about the "thinking" around benchmarks as I would like...

[Slow regex performance](https://forums.swift.org/t/slow-regex-performance/75768) seems like previous discussion although it doesn't have any answers.

---

<div class="post-metadata">

**Author:** ![LeoAvMo](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/leoavmo/32/45329_2.png) [@LeoAvMo](https://forums.swift.org/u/LeoAvMo)\
**Post date:** [October 12, 2026, 10:43pm UTC](https://forums.swift.org/t/benchmarking-different-regex-implementations/90008/4 "2026-10-12T22:43:55Z")

</div>

Thanks! I'll check out the documentation so I can ensure the benchmarks are more accurate 🙌
