Closed Bug 1376132 Opened 8 years ago Closed 8 years ago

The sameElements function in the Array extension file is highly innefficient-O(n^2)

Categories

(Firefox for iOS :: General, defect, P2)

Other
iOS
defect

Tracking

()

RESOLVED FIXED
Tracking Status
fxios 9.0 ---

People

(Reporter: bereket6725, Unassigned)

Details

(Whiteboard: [MobileCore])

Attachments

(1 file)

User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8 Steps to reproduce: While browsing the source code I noticed that the sameElements function in the Array extension file was very slow. I believe in the original version someone had also commented that it was inefficient but worked, so I figured I'd help make faster :) Actual results: This was the original algorithm, arr.contains(...) is a linear search that calls a function that does another linear search at each step. The operation ends up being O(n^2) // Laughably inefficient, but good enough for a handful of items. func sameElements(_ arr: [Element], f: (Element, Element) -> Bool) -> Bool { return self.count == arr.count && every { arr.contains($0, f: f) } } func contains(_ x: Element, f: (Element, Element) -> Bool) -> Bool { for y in self { if f(x, y) { return true } } return false } Expected results: You can compare two unsorted collections and make it a nlog(n) operation by sorting them both and comparing them.
forgot to add the "every" function so you can see the sameElements in its proper context: public extension Sequence { func every(_ f: (Self.Iterator.Element) -> Bool) -> Bool { for x in self { if !f(x) { return false } } return true } }
headsup, sent a pull request with a fix with the Bug # and title
Priority: -- → P2
Status: UNCONFIRMED → RESOLVED
Closed: 8 years ago
Resolution: --- → FIXED
Whiteboard: [MobileCore]
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Creator:
Created:
Updated:
Size: