Skip to content

Avoid two uses of defer {} #14868

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 28, 2018
Merged

Avoid two uses of defer {} #14868

merged 1 commit into from
Feb 28, 2018

Conversation

dabrahams
Copy link
Contributor

Last time I checked, things done in defer were not well-optimized and could cause closure allocation.

Last time I checked, things done in defer were not well-optimized and could cause closure allocation.
@dabrahams
Copy link
Contributor Author

@swift-ci please test and merge

@jckarter
Copy link
Contributor

jckarter commented Feb 27, 2018

Closure allocation overhead should not be a problem for defer. The "closure" is immediately invoked so we'll pass any "captures" immediately instead of putting them on the heap. The call can then be trivially inlined. I just tried swiftc -O with a simple example and this seemed to be the case. If there is a problem, we ought to fix trivial optimizer bugs like this instead of making the code more brittle.

@swift-ci swift-ci merged commit 619387f into master Feb 28, 2018
@Mazyod
Copy link
Contributor

Mazyod commented Feb 28, 2018

I apologize if this is irrelevant, but I can see that the PR subtly changes the semantics of the function, besides avoiding defer statement. Using defer will guarantee the _fixLifetime to be called in the event that an error is thrown, while using a temporary variable skips that call.

// prints "d" then "a"
do { 
    defer { print("d") }
    try throwSomething() 
} catch _ { 
    print("a") 
} 

@jckarter
Copy link
Contributor

It's probably harmless in this case since _fixLifetime is primarily a compiler hint, but yeah, in general this is an unwise transformation, because defer more safely handles hidden control flow edges, and does not have the overhead Dave seems to think it does.

@dabrahams
Copy link
Contributor Author

Dang. I’ll revert this as soon as I get to a keyboard

@jrose-apple jrose-apple deleted the kill-2-defers branch March 1, 2018 21:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants