What's the difference between using CGFloat and float?

前端 未结 5 604
忘了有多久
忘了有多久 2020-11-30 18:02

I tend to use CGFloat all over the place, but I wonder if I get a senseless \"performance hit\" with this. CGFloat seems to be something \"heavier\" than float, right? At wh

5条回答
  •  孤独总比滥情好
    2020-11-30 18:52

    Objective-C

    From the Foundation source code, in CoreGraphics' CGBase.h:

    /* Definition of `CGFLOAT_TYPE', `CGFLOAT_IS_DOUBLE', `CGFLOAT_MIN', and
       `CGFLOAT_MAX'. */
    
    #if defined(__LP64__) && __LP64__
    # define CGFLOAT_TYPE double
    # define CGFLOAT_IS_DOUBLE 1
    # define CGFLOAT_MIN DBL_MIN
    # define CGFLOAT_MAX DBL_MAX
    #else
    # define CGFLOAT_TYPE float
    # define CGFLOAT_IS_DOUBLE 0
    # define CGFLOAT_MIN FLT_MIN
    # define CGFLOAT_MAX FLT_MAX
    #endif
    
    /* Definition of the `CGFloat' type and `CGFLOAT_DEFINED'. */
    
    typedef CGFLOAT_TYPE CGFloat;
    #define CGFLOAT_DEFINED 1
    

    Copyright (c) 2000-2011 Apple Inc.

    This is essentially doing:

    #if defined(__LP64__) && __LP64__
    typedef double CGFloat;
    #else
    typedef float CGFloat;
    #endif
    

    Where __LP64__ indicates whether the current architecture* is 64-bit.

    Note that 32-bit systems can still use the 64-bit double, it just takes more processor time, so CoreGraphics does this for optimization purposes, not for compatibility. If you aren't concerned about performance but are concerned about accuracy, simply use double.

    Swift

    In Swift, CGFloat is a struct wrapper around either Float on 32-bit architectures or Double on 64-bit ones (You can detect this at run- or compile-time with CGFloat.NativeType) and cgFloat.native.

    From the CoreGraphics source code, in CGFloat.swift.gyb:

    public struct CGFloat {
    #if arch(i386) || arch(arm)
      /// The native type used to store the CGFloat, which is Float on
      /// 32-bit architectures and Double on 64-bit architectures.
      public typealias NativeType = Float
    #elseif arch(x86_64) || arch(arm64)
      /// The native type used to store the CGFloat, which is Float on
      /// 32-bit architectures and Double on 64-bit architectures.
      public typealias NativeType = Double
    #endif
    

    *Specifically, longs and pointers, hence the LP. See also: http://www.unix.org/version2/whatsnew/lp64_wp.html

提交回复
热议问题