且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一个iOS应用可以使用多少内存?

更新时间:2023-01-07 20:52:44

我编写了一个测试应用程序,用于测量应用程序在被终止之前可以分配多少内存.以下是数字:

I wrote a test app that measures how much memory an app can allocate before it's killed. Here are the numbers:

  • iPhone 5s(iOS 10,调试模式,1GB 内存):可分配 600MB
  • iPad Air 2(iOS 11.4,2GB 内存):可分配 1.3GB
  • iPhone X(iOS 11.4,3GB 内存):可分配 1.2GB
  • iPhone 7 Plus(iOS 12.1,3GB 内存):可分配 1.8GB
  • iPad 13 英寸(iOS 11.4,4GB 内存):可分配 3GB

有趣的是,我从未收到过内存警告.

It's interesting that I never got a memory warning.

如果您想自己运行测试,这里是代码:

Here's the code if you want to run the test yourself:

import UIKit

let sizeInMb = 100

class Wrapper {
  var array = [UInt8](repeating: 0, count: sizeInMb * 1048576)  // 100 MB
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        var i = 0

        sleep(5)  // So that you can see how much memory it consumes before any allocations.

        while true {
            let w = Wrapper()
            Unmanaged<Wrapper>.passRetained(w)
            i += 1
            print("(i * sizeInMb) MB allocated")
            sleep(1)  // Give the OS a chance to kill other processes.
        }

        return true
    }

    func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
        print("Memory warning!")
    }
}

这在模拟器上不起作用.任何有关性能的内容都应在设备上进行测试.

This does not work on the simulator. Anything regarding performance should be tested on device.