OC 内存对齐

93 阅读1分钟
  • sizeof 获取类型所占内存大小
NSLog(@"int: %lu",sizeof(int));
NSLog(@"double: %lu",sizeof(double));
NSLog(@"char: %lu",sizeof(char));
NSLog(@"short: %lu",sizeof(short));
NSLog(@"long: %lu",sizeof(long));
int: 4
double: 8
char: 1
short: 2
long: 8
  • class_getInstanceSize 实际所需内存
  • malloc_size 系统分配内存
NSObject *object = [[NSObject alloc] init];
NSLog(@"类型所占内存: %lu",sizeof(object));
NSLog(@"实际所需内存: %zu",class_getInstanceSize([NSObject class]));
NSLog(@"系统分配内存: %zu",malloc_size((__bridge const void *)(object)));
    
类型所占内存: 8
实际所需内存: 8
系统分配内存: 16
@interface Person : NSObject

//@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)NSInteger age;
@property(nonatomic,assign)int no;
//@property(nonatomic,assign)double height;
//@property(nonatomic,strong)Country *country;

@end
Person *person = [[Person alloc] init];
NSLog(@"类型所占内存: %lu",sizeof(person));
NSLog(@"实际所需内存: %zu",class_getInstanceSize([Person class]));
NSLog(@"系统分配内存: %zu",malloc_size((__bridge const void *)(person)));
    
类型所占内存: 8
实际所需内存: 24
系统分配内存: 32
  • 内存对齐

内存对齐原则其实可以简单理解为min(m,n)——m为当前开始的位置,n为所占位数。当m是n的整数倍时,条件满足;否则m位空余,m+1,继续min算法。

大神链接