How to merge multiple Arrays without slowing the compiler down?

半城伤御伤魂 提交于 2019-12-05 00:23:03

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/39490808/how-to-merge-multiple-arrays-without-slowing-the-compiler-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!