空的for循環不耗性能,基本不耗時
#pragma mark - 耗時操作 - (void)longOperation { // 性能測試: double start = CACurrentMediaTime(); for (int i = 0; i < 1000000; i++) { //循環內沒有任操作 } // 獲取時間差值 NSLog(@"----:%f",CACurrentMediaTime() - start); }
打印結果:2017-06-19 18:57:25.465 01-模擬耗時操作[95446:4223426] —-:0.002655
操作內存的棧區不耗性能,基本不耗時,因爲地址是連續的,尋址簡單
#pragma mark - 耗時操作 - (void)longOperation { // 性能測試: double start = CACurrentMediaTime(); for (int i = 0; i < 1000000; i++) { //定義一個int類型 -- 該變量存放在內存的棧區 int abc = 10000000; } // 獲取時間差值 NSLog(@"----:%f",CACurrentMediaTime() - start); }
打印結果:2017-06-19 19:00:02.243 01-模擬耗時操作[95474:4224838] —-:0.002460
操作內存的常量區不耗性能,相對不耗時,但是相對棧區要耗性能一些,內存控件只開闢一次
#pragma mark - 耗時操作 - (void)longOperation { // 性能測試: double start = CACurrentMediaTime(); for (int i = 0; i < 1000000; i++) { // 定義一個NSString字符串 -- 該變量存放在內存的常量區 NSString *str = @"aaaaaaaaaaaaaaaaaaaaaaaa"; } // 獲取時間差值 NSLog(@"----:%f",CACurrentMediaTime() - start); }
打印結果:2017-06-19 19:03:57.907 01-模擬耗時操作[95515:4226915] —-:0.011038
操作內存的堆區,相對棧區和常量區要耗更多性能,因爲堆區的地址是不連續的,需要耗費時間去尋址
#pragma mark - 耗時操作 - (void)longOperation { // 性能測試: double start = CACurrentMediaTime(); for (int i = 0; i < 1000000; i++) { // 該變量存放在內存的堆區 NSString *str = [NSString stringWithFormat:@"test--%d",i]; } // 獲取時間差值 NSLog(@"----:%f",CACurrentMediaTime() - start); }
打印結果:2017-06-19 19:17:28.997 01-模擬耗時操作[95598:4233527] —-:0.804514
I/O操作是非常耗性能的
#pragma mark - 耗時操作 - (void)longOperation { // 性能測試: double start = CACurrentMediaTime(); for (int i = 0; i < 1000000; i++) { // 打印非常耗時也就是耗時操作 NSLog(@"%d",i); } // 獲取時間差值 NSLog(@"----:%f",CACurrentMediaTime() - start); }
打印結果:2017-06-19 19:11:29.560 01-模擬耗時操作[95554:4229094] —-:176.182018
耗時操作對UI交互影響:會卡死UI導致屏幕上的空間暫時無法執行操作
不同內存區域的耗時操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.