文章目录
一、Allocations(监测内存分配)
1、简介
2、如何使用
一、Allocations
1、简介
性能优化中使用Instruments-Allocations工具进行内存分配使用监测。
内存爆增,且持续不释放的情况,除了是内存泄露外,还有就是对性能代码质量不过关导致。
Allocations能够帮你精准定位到内存占用过多的代码。
注意事项 : 一定要用真机。
2、如何使用
下面图文配合演示操作过程
(1) 创建project,命名为AllocationsDemo。在控制器添加一个UITableview实例,并在创建cell代理方法里面添加占用内存代码,在IPhonex模拟下运行工程。如下
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
//占用内存过高的代码
for (int i = 0; i < 100; i++) {
UIView *view = [[UIView alloc]init];
view.backgroundColor = [UIColor redColor];
}
cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
我们的目标 :通过Allocations将这段耗内存的代码找出来。
(2) 打开Instruments(X-code -> Open Developer Tool -> Instruments),选中性能测试项目,选择检测内存分配,choose。
.
(3) 选择完成后,进入如下页面,开始录制,并在内存上涨的地方Mark Generation 做下标下。如下
.
(4) 设置Call Tree 设置选项(这边跟检测内存泄露Leak是一样的)
我习惯选择是 :勾选Separate by Categoty 和 Hide System Libratiese
.
(5) 切换导航到Generations, 列表上分别有GenerationA、GenerationB、GenerationC。三个标记样本。最好多标记几个”样本”,便于分析。
.
(6) 点击”样本”旁边的箭头进一步分析内存分配。在此选择GenerationB分析。
.
(7) 进而”找到占用过多内存的代码”