0%

alloc的size分析

定义如下一个类:

1
2
3
4
5
6
7
8
@interface Person : NSObject
@property (nonatomic,assign) int height;
@property (nonatomic,assign) int age;
@property (nonatomic,assign) int no;
@end

@implementation Person
@end

将其转换为C++代码:

1
2
3
4
5
6
7
8
9
10
11
struct NSObject_IMPL {
Class isa;
};

struct Person_IMPL {
struct NSObject_IMPL NSObject_IVARS; //8个字节
int _height; //4个字节
int _age; //4个字节
int _no; //4个字节
};

根据分析可知,Person_IMPL结构体内所有成员的总大小为20个字节,但由于内存对齐的原因,Person_IMPL结构体占用的内存大小应为24个字节。

实际上,使用class_getInstanceSize打印的结果为24,但是使用malloc_size打印的结果为32. 可见,Person实例对象实际占用的内存大小为32字节,尽管其只使用了24个字节。

alloc方法底层调用的方法为allocWithZone, 而allocWithZone方法则会调用calloc函数分配内存. 相关的源码可以在https://opensource.apple.com/tarballs/libmalloc/进行下载。

根据源码可以发现,系统为了优化内存的使用效率,规定iOS中分配的内存大小都必须为16的倍数.