iOS 内存对齐原理

2021-02-08  本文已影响0人  辉辉岁月

获取内存大小

第一种:sizeof

The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type(including aggregate types). This keyword returns a value of type size_t.

第二种:class_getInstanceSize

alloc&init原理

第三種:malloc_size

測試

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;

@end
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Person.h"
#import <objc/runtime.h>
#import <malloc/malloc.h>

int main(int argc, char * argv[]) {
 @autoreleasepool {
     Person *p1 = [[Person alloc] init];
     NSLog(@"p1对象类型占用的内存大小:%lu",sizeof(p1));
     NSLog(@"p1对象实际占用的内存大小:%lu",class_getInstanceSize([p1 class]));
     NSLog(@"p1对象实际分配的内存大小:%lu",malloc_size((__bridge const void *)(p1)));
 }
 return 0;
}
p1对象类型占用的内存大小:8
p1对象实际占用的内存大小:24
p1对象实际分配的内存大小:32

为什么

结构体内存对齐规则

规则一

规则二

规则三

內存对齐的原因

数据类型对应的字节数表格

数据类型对应的字节数

范例一

struct StructA {
    double a;   // 8 (0-7)
    char b;     // 1 [8 1] (8)
    int c;      // 4 [9 4] 9 10 11 (12 13 14 15)
    short d;    // 2 [16 2] (16 17)
} strA;
struct StructB {
    double a;   //8 (0-7)
    int b;      //4 (8 9 10 11)
    char c;     //1 (12)
    short d;    //2 13 (14 15) - 16
} strB;

// 輸出
NSLog(@"strA = %lu,strB = %lu", sizeof(strA), sizeof(strB));
strA = 24,strB = 16

详解:

strutA:

strutB:

范例二:

结构体嵌套结构体

struct StructA {
    double a;   // 8字節
    char b;     // 1字節 
    int c;      // 4字節 
    short d;    // 2字節 
} strA;
struct StructB {
    double a;   //8字節 
    int b;      //4字節 
    char c;     //1字節
    short d;    //2字節 
} strB;
struct StructC {
   double a;   //8字節
   int b;      //4字節
   char c;     //1字節
   short d;    //2字節
struct StructB str;    //16字節
} strC;

// 輸出
NSLog(@"strA = %lu,strB = %lu,strC = %lu", sizeof(strA), sizeof(strB), sizeof(strC));
strA = 24,strB = 16,strC = 32

詳解

structC

内存优化(属性重排)

通过刚刚范例,我們可以得出一個结论,结构体內存大小与结构体成源內存大小的顺序有关

下面來了一個例子說明苹果属性重排,即內存优化

@interface LGPerson : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *nickName;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) long height;

@property (nonatomic) char c1;
@property (nonatomic) char c2;
@end
int main(int argc, char * argv[]) {
    @autoreleasepool {
       LGPerson *p1 = [LGPerson alloc];
        p1.name      = @"Cooci";
        p1.nickName  = @"帥哥";
        p1.age       = 18;
        p1.c1        = 'a';
        p1.c2        = 'b';

        LGPerson *p2 = [p1 init];
        p2.name      = @"C.C";
        p2.nickName  = @"美女";
        p2.age       = 18;
        p2.c1        = 'a';
        p2.c2        = 'b';
    }
    return 0;
}

alloc&init原理

总结-內存对齐:

內存是通過固定的内存块进行读取
苹果会自动对属性依据原则进行重排,进行内存优化

上一篇 下一篇

猜你喜欢

热点阅读