首页 > 解决方案 > 将公共函数的实现隐藏在私有函数中是否有任何性能优势或编译时间改进

问题描述

例如说我有一个 CarModel

struct CarModel: Codable {
    var numberPlate: String
    var vin: String
    var model: String
    var fuel: Double
    var position: Position
}

我有一个公共方法

extension CarModel {
    var fuelString: String {
        return fuelStringImplementation
    }
}

但是我没有在公共方法中实现,而是将其隐藏在私有方法后面。

private extension CarModel {
    var fuelStringImplementation: String {
        if fuel == 0.0 {
            return "car_list_item_tank_empty".localizedString()
        }
        let fuelDouble = fuel*100
        let finalString = String(format: "car_list_item_tank_status".localizedString(), fuelDouble)
        return finalString
    }
}

而对于 cellForAtIndexPath 我可以将实现隐藏在这样的私有方法中

private func collectionViewImplementation(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MainImageCollectionViewCell.className, for: indexPath)
    guard let model = viewModel.modelForIndex(index: indexPath.row) else {
        assertionFailure("model is nil")
        return cell
    }
    guard let mainImageCell = cell as? MainImageCollectionViewCell else {
        assertionFailure("cell is not type MainImageCollectionViewCell")
        return cell
    }
    mainImageCell.fill(with: model)
    return mainImageCell
}

标签: swiftperformance

解决方案


不,为了性能优势,方法是私有的还是公共的都没有关系。如果我们谈论函数和性能改进(更不用说该函数的主体实现),我们应该更接近方法调度类型。其中有一些:动态、表格和直接。例如,直接具有最佳性能。这是一个巨大的主题,所以我建议你在网上阅读一些关于它的文章。像这样,例如https://developer.apple.com/swift/blog/?id=27


推荐阅读