[swift-corelibs-dev] Memory leak with String.range(options: .regularExpression) [SR-3536]

Nethra Ravindran nethraravindran94 at gmail.com
Wed Feb 8 01:44:48 CST 2017

Hi everyone,

I am working on https://bugs.swift.org/browse/SR-3536

There is a memory leak when searching for the substring of a string using
regular expression.

import Foundation

let myString = "Foo"
for _ in 1...10000 {
  let _ = myString.range(of: "bar", options: .regularExpression)

>From the above test case i could see that over a period of time, around 60
Mb of memory was leaked.

I see in String.range we eventually call NSString._createRegexForPattern.
Here we maintain a mapping between NSString and NSRegularExpression object
in NSCache<NSString, NSRegularExpression>. All the entries in the cache are
maintained in a dictionary ( _entries ) which takes the UnsafeRawPointer as
the key, which seems to be the address of the NSString Object and
NSCachedEntry as value.

Though the pattern is of type String, it is stored in the NSCache as
NSString. And since we are storing the NSCachedEntry objects in a
dictionary indexed by the address (UnsafeRawPointer) of the NSString
object, there is a new cache entry created for each iteration ( in the test
case ) though the pattern string remains the same.

Can someone guide me about how to go about resolving this issue.

Thank you.

- Nethra Ravindran
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-corelibs-dev/attachments/20170208/fa5ec668/attachment.html>

More information about the swift-corelibs-dev mailing list