Prepending something to the beginning of an array

which is better?

func path(to target:Target) -> [String]
{
    [self.prefix] + target.generatePath()
}
func path(to target:Target) -> FlattenSequence<[[String]]>
{
    [[self.prefix], target.generatePath()].joined()
}
func path(to target:Target) -> [String]
{
    var path:[String] = [self.prefix]
    // requires refactoring `Target.generatePath`
    target.generatePath(into: &path)
    return path
}

"Better" in what way? Conciseness, readability, performance / minimal execution overhead, something else?

One additional, more explicit, option:

func path(to target: Target) -> [String] {
    var path = target.generatePath()
    path.insert(self.prefix, at: path.startIndex)
    return path
}

(I would personally tend to this option, or your first, as a matter of style — but it depends what specifically you're going for.)

1 Like

“better“ in general. clearly, option #3 is best for performance, but is worst in readability. what i am curious about is if the optimizer is advanced enough that we can write #1 (which is superior in readability) and still get the same performance as #3.