直接返回bool语句VS使用if返回bool

时间:2016-10-24 07:34:13

标签: ios swift

有一个问题我现在真的很想问。 查看Swift中的以下代码

import UIKit

var str = "Hello, playground"
var flag = true

func checkA() -> Bool{
    if str == "Hello, playground" && flag == true {
        return true
    }
    return false
}

func checkB() -> Bool{
    return str == "Hello, playground" && flag == true
}

checkA()
checkB()

可以看到' checkA()'和' checkB()'基本上是相同的功能,因为它每次都返回相同的值。在我看来(我从不擅长编程),我更喜欢&checka()'因为它比checkB()更具可读性。任何人都可以阅读' checkA()'并且只知道它的意思但人们(或许只是我)需要考虑checkB()中发生的事情。

使用checkB()代替checkA()是否有任何性能优势,或者这只是偏好?

2 个答案:

答案 0 :(得分:1)

我认为这些内容没有任何性能变化,checkB()代码较少且更清晰,但checkA()更具可读性。由您决定使用的是什么。

答案 1 :(得分:1)

在相同的优化设置下,这两个人应该(理论上)最终都是一样的。

我决定让Xcode告诉我,这更快(也是使用measure中的XCTest块的借口)

enter image description here

答案是checkB() FTW!

这里需要注意的是,我刚刚创建了一个全新的Xcode项目并输入了此代码 - 没有使用优化设置或其他任何内容

测试代码

import XCTest
@testable import BoolTest

class BoolTestTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    var str = "Hello, playground"
    var flag = true

    func checkA() -> Bool{
        if str == "Hello, playground" && flag == true {
            return true
        }
        return false
    }

    func checkB() -> Bool{
        return str == "Hello, playground" && flag == true
    }

    func testA() {
        self.measure {
            for _ in 1...1000000 {
                let _ = self.checkA()
            }
        }
    }

    func testB() {
        self.measure {
            for _ in 1...1000000 {
            let _ = self.checkB()
            }
        }
    }
}
相关问题