Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple Arrays without slowing the compiler down?

Adding this line of code causes my compile time to go from 10 seconds to 3 minutes.

var resultsArray = hashTagParticipantCodes + prefixParticipantCodes + asterixParticipantCodes + attPrefixParticipantCodes + attURLParticipantCodes

Changing it to this brings the compile time back down to normal.

var resultsArray = hashTagParticipantCodes
resultsArray += prefixParticipantCodes
resultsArray += asterixParticipantCodes
resultsArray += attPrefixParticipantCodes
resultsArray += attURLParticipantCodes

Why does the first line cause my compile time to slow down so drastically and is there a more elegant way to merge these Arrays than the 5 line solution I've posted?

like image 493
Declan McKenna Avatar asked Sep 14 '16 12:09

Declan McKenna


People also ask

How do you append multiple arrays into an array of arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do I merge multiple arrays in node JS?

The concat() method is used to merge two or more arrays and is built directly into the Node. js language. It doesn't change anything about the existing arrays and just simply combines them into one new array.

How do you merge two arrays using the spread Operator?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.


1 Answers

It's always +. Every time people complain about explosive compile times, I ask "do you have chained +?" And it's always yes. It's because + is so heavily overloaded. That said, I think this is dramatically better in Xcode 8, at least in my quick experiment.

You can dramatically speed this up without requiring a var by joining the arrays rather than adding them:

let resultsArray = [hashTagParticipantCodes,
                    prefixParticipantCodes,
                    asterixParticipantCodes, 
                    attPrefixParticipantCodes,
                    attURLParticipantCodes]
                   .joinWithSeparator([]).map{$0}

The .map{$0} at the end is to force it back into an Array (if you need that, otherwise you can just use the lazy FlattenCollection). You can also do it this way:

let resultsArray = Array(
                   [hashTagParticipantCodes,
                    prefixParticipantCodes,
                    asterixParticipantCodes, 
                    attPrefixParticipantCodes,
                    attURLParticipantCodes]
                   .joinWithSeparator([]))

But check Xcode 8; I believe this is at least partially fixed (but using .joined() is still much faster, even in Swift 3).

like image 135
Rob Napier Avatar answered Sep 30 '22 05:09

Rob Napier