What's the difference between using CGFloat and float?
Asked Answered
S

5

177

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 which points should I use CGFloat, and what makes really the difference?

Scuba answered 12/8, 2009 at 8:26 Comment(0)
I
201

As @weichsel stated, CGFloat is just a typedef for either float or double. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.

These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float precision within your own code, you can still use float if you like — it will reduce your memory footprint somewhat. Same goes for integer values.

I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.

Indoors answered 12/8, 2009 at 13:16 Comment(6)
I think I get it now. But on the iPhone it seems to not matter much, right?Scuba
On the iPhone as we know it, no. However, it's always wise to future-proof code, and this would make it easier to safely reuse the same code for OS X.Indoors
so you're saying, basically, NEVER use a float or double directly since then you'd be tied to the processor architecture (and I thought fast JVMs solved this years ago :)). So what primitives are safe? int?Highborn
I didn't say NEVER use a primitive directly. There are times that straight primitives can be problematic, such as if a variable may conceivably be used to store data which could overflow, such as on 64-bit. In general, using architecture-dependent typedefs is safer, in that code is less likely to explode on a different architecture. However, sometimes using a 32-bit type can be completely safe and save you memory. The size of primitives may be less of an issue in a JVM, but Obj-C and C are compiled, and mixing 32 and 64 bit libraries and code is indeed problematic.Indoors
@QuinnTaylor can you provide a practical example of how float would overflow while CGFloat would not? Both float and CGFloat have a finite number of bits. You can overflow both of them by needing to store more bits than they can hold.Mithgarthr
One place this overflows is when using float/double as method return values like (double)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath. That will cause problems on 32-bit systems while working fine on 64-bit systems, thus being extremely hard to find/debug. The solution is to use CGFloat here. This is arguably a slightly contrived example, but a valid one.Hysterotomy
G
78

CGFloat is a regular float on 32-bit systems and a double on 64-bit systems

typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit

So you won't get any performance penalty.

Grammalogue answered 12/8, 2009 at 8:31 Comment(7)
Well, you use twice as much memory, if you're worried about memory.Neglectful
Correct, iPhone OS is 32-bit. If you think about it, the iPhone isn't pushing the 4GB RAM limitation of 32-bit, nor is it using an Intel processor (for which 64-bit is faster than 32-bit). Plus, it's using Modern Runtime (as opposed to Legacy Runtime of 32-bit on the desktop — wearch SO for these terms if you're curious) so it can do basically everything 64-bit OS X can. Perhaps someday we'll see a device that runs iPhone OS and is 64-bit, but currently there are none.Indoors
You won't necessarily use "twice as much memory". In most normal situations on 64 bit architectures, you're going to align on 64 bit boundaries anyway, so if you allocated memory or define structs limited to 32 bit types, unless you personally are packing/unpacking pairs of 32 bit values into 64 bit words, you are probably going to end up with 64 bit underlying storage anyway.Courthouse
5S is now in 64 bit, last time I entered the conference (london), they said the way they run 32-bit apps on ios7 is to init another shared cache pool in memory, which can result in using more memory overall. so its def worth to convert everything up to 64-bits. (unless you want to support 5.1+ or 6.0+ still)Holierthanthou
Is it safe to put a CGFloat into NSNumber: [NSNumber numberWithFloat:myCGFloatVar]Jennajenne
You should use [NSNumber numberWithDouble:myCGFloatVar] because CGFloat is defined as double on 64-bit platforms.Grammalogue
Let's add that: 1. The 32 bit float is the correct choice where ever code consistency is required. 2. But once aligned on 64 Bit CPU it costs the same memory as if it was 64 bit (so, 32 bits are wasted). 3. While CGFloat allows you to use the maximum the system has to offer!Danaedanaher
P
3

As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.

Pity answered 20/11, 2015 at 19:35 Comment(0)
D
3

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

Dilly answered 30/12, 2015 at 20:12 Comment(2)
CGFloat also has an instance property called native that returns self in the native type (Float or Double as specified above).Butterball
Thanks for pointing that out, @PeterSchorn! Not sure why I didn't mention it in the answerDilly
C
2

just mention that - Jan, 2020 Xcode 11.3/iOS13

Swift 5

From the CoreGraphics source code

public struct CGFloat {
    /// 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
Consumer answered 7/1, 2020 at 9:15 Comment(1)
So CGFloat is always a Double as of Swift 5?Butterball

© 2022 - 2024 — McMap. All rights reserved.