user7065798
user7065798

Reputation: 103

Swift. Storing big array of numbers and calculating average value

Let me give an example. During 5 hours I will receive data, Doubles (with 0-2 values, such as 1.4525), the total amount of values will be up to 5-10k, so it will be several values per second. I need to store it somewhere during that session and after it calculate average value of all values. The app will work in a foreground.

I am not sure how to do to such big about of data. So, have 2 questions:

Upvotes: 0

Views: 598

Answers (1)

Duncan C
Duncan C

Reputation: 131471

10,000 doubles, at 8 bytes per item, is only 80,000 bytes (80k). That's a pretty small amount of data. You can use an in-memory array of Doubles for that.

Performance-wise, it would take a modern iPhone a fraction of a second to do 10,000 additions and a division. You can calculate the average any time you want without much speed penalty. It's only if you're doing it over and over in a loop where you'd see a performance penalty.

As pvg pointed out in his comment, if all you ever need is the average then you can simply store a sum and the number of values, which would only be 2 doubles, not 10,000 of them. (You'd just add each new value to the sum, increment the count, and then recalculate the average as:

ave = sum/count

You could also cast your array to an NSArray and write it to a plist quite easily.

Upvotes: 2

Related Questions