Fattie
Fattie

Reputation: 12590

"Appending" to an ArraySlice?

Say ...

What about ...

var thingsBacking = [Thing](repeating: Thing(), count: 100) // hard limit!
var things: ArraySlice<Thing> = []

func fatCalculation() {

    var pin: Int = 0
    // happily, no need to clean-out thingsBacking
    for c in .. some huge loop {

        ... only some of the items (roughly 20 say) become the result
        x = .. one of the result items

        thingsBacking[pin] = Thing(... x, y, z )
        pin += 1
    }

    // and then, magic of slices ...
    things = thingsBacking[0..<pin]

(Then, you can do this anywhere... for t in things { .. } )

What I am wondering, is there a way you can call to an ArraySlice<Thing> to do that in one step - to "append to" an ArraySlice and avoid having to bother setting the length at the end?

So, something like this ..

things = ... set it to zero length
things.quasiAppend(x)
things.quasiAppend(x2)
things.quasiAppend(x3)

With no further effort, things now has a length of three and indeed the three items are already in the backing array.

I'm particularly interested in performance here (unusually!)

Another approach,

var thingsBacking = [Thing?](repeating: Thing(), count: 100) // hard limit!

and just set the first one after your data to nil as an end-marker. Again, you don't have to waste time zeroing. But the end marker is a nuisance.

Is there a more better way to solve this particular type of array-performance problem?

Upvotes: 1

Views: 382

Answers (1)

Fattie
Fattie

Reputation: 12590

Based on MartinR's comments, it would seem that for the problem

  • the data points are incoming and
  • you don't know how many there will be until the last one (always less than a limit) and
  • you're having to redo the whole thing at high Hz

It would seem to be best to just:

(1) set up the array

var ra = [Thing](repeating: Thing(), count: 100) // hard limit!

(2) at the start of each run,

 .removeAll(keepingCapacity: true)

(3) just go ahead and .append each one.

(4) you don't have to especially mark the end or set a length once finished.

It seems it will indeed then use the same array backing. And it of course "increases the length" as it were each time you append - and you can iterate happily at any time.

Slices - get lost!

Upvotes: 1

Related Questions