Skip to content

Commit c58eed6

Browse files
committed
Merge pull request #9 from Adlai-Holler/InitWithCapacity
Use Array.reserveCapacity in NSArray/NSMutableArray
2 parents a1c68cd + 0c784b7 commit c58eed6

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

Foundation/NSArray.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NS
6969
}
7070

7171
public required init(objects: UnsafePointer<AnyObject?>, count cnt: Int) {
72+
_storage.reserveCapacity(cnt)
7273
for idx in 0..<cnt {
7374
_storage.append(objects[idx]!)
7475
}
@@ -500,6 +501,10 @@ public class NSMutableArray : NSArray {
500501

501502
public init(capacity numItems: Int) {
502503
super.init(objects: nil, count: 0)
504+
505+
if self.dynamicType === NSMutableArray.self {
506+
_storage.reserveCapacity(numItems)
507+
}
503508
}
504509

505510
public required convenience init(objects: UnsafePointer<AnyObject?>, count cnt: Int) {
@@ -599,6 +604,7 @@ public class NSMutableArray : NSArray {
599604
public func replaceObjectsInRange(range: NSRange, withObjectsFromArray otherArray: [AnyObject], range otherRange: NSRange) { NSUnimplemented() }
600605
public func replaceObjectsInRange(range: NSRange, withObjectsFromArray otherArray: [AnyObject]) {
601606
if self.dynamicType === NSMutableArray.self {
607+
_storage.reserveCapacity(count - range.length + otherArray.count)
602608
for var idx = 0; idx < range.length; idx++ {
603609
_storage[idx + range.location] = otherArray[idx]
604610
}
@@ -622,6 +628,10 @@ public class NSMutableArray : NSArray {
622628
public func insertObjects(objects: [AnyObject], atIndexes indexes: NSIndexSet) {
623629
precondition(objects.count == indexes.count)
624630

631+
if self.dynamicType === NSMutableArray.self {
632+
_storage.reserveCapacity(count + indexes.count)
633+
}
634+
625635
var objectIdx = 0
626636
indexes.enumerateIndexesUsingBlock() { (insertionIndex, _) in
627637
self.insertObject(objects[objectIdx++], atIndex: insertionIndex)

0 commit comments

Comments
 (0)