老谭笔记

快速计算目录的size

关于目录的size计算,我尝试过很多种方式去实现过,虽然都已经应用在正式的项目之中,但我一直对其性能不满意。最常见的就是通过递归方式去逐层计算,但通过测试发现在计算层数多、数量大的目录时,递归的方式会消耗很大的栈空间,甚至出现栈溢出,当然效率也会是很大的瓶颈。最初通过将NSFileManager获取单个文件size修改为FS的函数提升效率,到后来改用效率更高的stat方式,并且不仅可能获得文件实际大小,也能获得占用磁盘的大小。另外通过自己实现栈的方式去替换掉递归,不仅节省了内存占用,让效率也有大幅的提升。

下面就是具体的代码实现,通过NSMutableArray来模拟栈(经测试用数组头作为栈顶相比数组尾部做栈顶效率更高,这与NSMutableArray内部实现有关,也尝试不依赖NSMutableArray而去实现栈但效率提升有限),并通过diskMode参数可返回是否是磁盘占用的size:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
+ (uint64_t)sizeAtPath:(NSString *)filePath diskMode:(BOOL)diskMode
{
uint64_t totalSize = 0;
NSMutableArray *searchPaths = [NSMutableArray arrayWithObject:filePath];
while ([searchPaths count] > 0)
{
@autoreleasepool
{
NSString *fullPath = [searchPaths objectAtIndex:0];
[searchPaths removeObjectAtIndex:0];
struct stat fileStat;
if (lstat([fullPath fileSystemRepresentation], &fileStat) == 0)
{
if (fileStat.st_mode & S_IFDIR)
{
NSArray *childSubPaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullPath error:nil];
for (NSString *childItem in childSubPaths)
{
NSString *childPath = [fullPath stringByAppendingPathComponent:childItem];
[searchPaths insertObject:childPath atIndex:0];
}
}else
{
if (diskMode)
totalSize += fileStat.st_blocks*512;
else
totalSize += fileStat.st_size;
}
}
}
}
return totalSize;
}