Skip to content
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

타입 추론과 타입 어노테이션의 속도 차이에 관하여 #86

Closed
Taehyeon-Kim opened this issue Aug 2, 2022 · 2 comments
Closed
Assignees

Comments

@Taehyeon-Kim
Copy link
Owner

Taehyeon-Kim commented Aug 2, 2022

타입 추론과 타입 어노테이션의 속도 차이에 관하여

그 동안 막연하게도 타입 어노테이션(명시)가 컴파일 속도가 더 빠르다고 생각했던지라 아무 생각 없이 타입 명시를 하는 습관을 들이고 있었다. 그러나 최근 듣고 있는 교육 과정에서 멘토님께서 타입 추론을 하는 것이 더 나아보인다라는 말씀을 해주셨고, 왜인지 궁금했던지라 여쭤보게 되었다. 답변 주신 것으로는 컴파일러의 성능이 점점 더 개선되고 있고, 타입 추론이 컴파일 속도가 더 빠르다는 실험 결과도 있다고 답변주셨다.

실제로 아래에 첨부한 링크를 보면 간단한 실험 결과를 확인해볼 수 있다.

let a = "hello, world!" // type is inferred
let b = String("hello, world!") // type is inferred from String(...) and then passed to the root (the constant b)
let c: String = .init("hello, world!") // type inference is not required
let d: String = "hello, world!" // type inference is not required

결과를 보면 1번(타입 추론)을 한 것이 속도가 가장 빨랐다.

Benchmark #1: xcrun swiftc -typecheck a.swift
  Time (mean ± σ):     175.7 ms ±   3.5 ms    [User: 82.9 ms, System: 81.9 ms]
  Range (min … max):   171.0 ms … 182.8 ms    16 runs

Benchmark #1: xcrun swiftc -typecheck b.swift
  Time (mean ± σ):     224.8 ms ±   2.8 ms    [User: 131.1 ms, System: 81.7 ms]
  Range (min … max):   220.2 ms … 228.2 ms    13 runs

Benchmark #1: xcrun swiftc -typecheck c.swift
  Time (mean ± σ):     672.3 ms ±   8.0 ms    [User: 568.3 ms, System: 93.7 ms]
  Range (min … max):   662.4 ms … 685.1 ms    10 runs

Benchmark #1: xcrun swiftc -typecheck d.swift
  Time (mean ± σ):     213.3 ms ±   2.0 ms    [User: 119.8 ms, System: 81.6 ms]
  Range (min … max):   210.2 ms … 216.5 ms    13 runs

나는 타입을 추론하는데 더 많은 리소스가 들 것이라고 그냥 생각하고 있었는데 타입 추론이 속도가 더 빠르다니... 물론 실험 결과 중 1가지이긴 하지만 되게 신기했다. 덧붙여서 멘토님께서는 타입을 명시하게 되면 컴파일러가 명시된 타입과 초깃값을 비교하는 작업이 추가되어서 더 느리고, 애초에 타입 명시와 타입 추론 속도 차이 자체도 밀리세컨드 단위 차이로 미세하다라고 말씀 해주셨다.

컴파일 성능 자체에 영향을 크게 주는 것이 아니라면, 타입 명시를 하나하나 해주는 것은 정말 비효율적인 작업일 것이다. 타입 추론을 하는 방향으로 코드 작성 습관을 바꾸도록 해야겠다. 그리고 확실한 근거 없이 막연히 무엇이 더 좋겠다라고 생각했던 나 자신을 반성하고자 한다.

@Taehyeon-Kim Taehyeon-Kim self-assigned this Aug 2, 2022
@Taehyeon-Kim
Copy link
Owner Author

@Taehyeon-Kim
Copy link
Owner Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant