Convert Figma logo to code with AI

Tencent logoMMKV

An efficient, small mobile key-value storage framework developed by WeChat. Works on Android, iOS, macOS, Windows, and POSIX.

17,252
1,893
17,252
6

Top Related Projects

Realm is a mobile database: a replacement for Core Data & SQLite

A type-safe, Swift-language layer over SQLite3.

13,842

A Cocoa / Objective-C wrapper around SQLite

A toolkit for SQLite databases, with a focus on application development

Simple Swift wrapper for Keychain that works on iOS, watchOS, tvOS and macOS.

The better way to deal with JSON data in Swift.

Quick Overview

MMKV is an efficient, small, and easy-to-use mobile key-value storage framework developed by Tencent. It uses memory mapping for fast read/write operations and protobuf for encoding/decoding, making it significantly faster than traditional key-value storage solutions.

Pros

  • High performance: Faster than SQLite and SharePreferences for key-value operations
  • Cross-platform support: Available for iOS, Android, macOS, Windows, and POSIX
  • Encryption support: Built-in AES encryption for data security
  • Efficient memory usage: Uses memory mapping for optimal performance and resource utilization

Cons

  • Limited query capabilities: Not suitable for complex data structures or relational data
  • Learning curve: Requires understanding of memory mapping and protobuf concepts
  • Size limitations: Not ideal for storing large amounts of data or binary files

Code Examples

  1. Initializing MMKV:
import com.tencent.mmkv.MMKV

MMKV.initialize(context)
val kv = MMKV.defaultMMKV()
  1. Writing and reading data:
// Writing data
kv.encode("bool", true)
kv.encode("int", 123)
kv.encode("string", "Hello MMKV")

// Reading data
val boolValue = kv.decodeBool("bool")
val intValue = kv.decodeInt("int")
val stringValue = kv.decodeString("string")
  1. Using encryption:
val encryptedKV = MMKV.mmkvWithID("encrypted", MMKV.MULTI_PROCESS_MODE, "encryption_key")
encryptedKV.encode("secret", "sensitive data")

Getting Started

To use MMKV in your Android project:

  1. Add the dependency to your app's build.gradle:

    dependencies {
        implementation 'com.tencent:mmkv:1.2.14'
    }
    
  2. Initialize MMKV in your Application class:

    class MyApplication : Application() {
        override fun onCreate() {
            super.onCreate()
            MMKV.initialize(this)
        }
    }
    
  3. Use MMKV in your code:

    val kv = MMKV.defaultMMKV()
    kv.encode("key", "value")
    val value = kv.decodeString("key")
    

Competitor Comparisons

Realm is a mobile database: a replacement for Core Data & SQLite

Pros of Realm Swift

  • Full-featured database solution with support for complex queries and relationships
  • Cross-platform compatibility (iOS, Android, and more)
  • Robust ecosystem with extensive documentation and community support

Cons of Realm Swift

  • Steeper learning curve due to its comprehensive feature set
  • Larger footprint and potentially slower performance for simple key-value storage

Code Comparison

MMKV (Key-Value Storage):

MMKV.default().set(42, forKey: "answer")
let value = MMKV.default().int32(forKey: "answer")

Realm Swift (Database Operations):

let realm = try! Realm()
try! realm.write {
    realm.add(MyObject(value: ["name": "John", "age": 30]))
}
let results = realm.objects(MyObject.self).filter("age > 25")

MMKV focuses on simple, high-performance key-value storage, while Realm Swift offers a more comprehensive database solution. MMKV is lightweight and efficient for basic data persistence, whereas Realm Swift provides advanced features like relationships, queries, and cross-platform support at the cost of increased complexity and resource usage. Choose MMKV for straightforward key-value storage needs, and Realm Swift for more complex data management requirements in larger applications.

A type-safe, Swift-language layer over SQLite3.

Pros of SQLite.swift

  • Full-featured SQLite database access with a type-safe Swift API
  • Supports complex SQL queries and transactions
  • Integrates well with existing SQLite databases and SQL-based workflows

Cons of SQLite.swift

  • Slower performance for simple key-value storage compared to MMKV
  • Requires more setup and configuration for basic use cases
  • Larger memory footprint due to SQLite engine

Code Comparison

SQLite.swift:

let db = try Connection("path/to/db.sqlite3")
try db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
try db.run("INSERT INTO users (name) VALUES (?)", "Alice")
let users = try db.prepare("SELECT * FROM users")
for user in users {
    print("User: \(user[1])")
}

MMKV:

let mmkv = MMKV(mmapID: "myMMKV")
mmkv.set("Alice", forKey: "user")
let user = mmkv.string(forKey: "user")
print("User: \(user ?? "")")

SQLite.swift provides a more powerful and flexible database solution, suitable for complex data structures and queries. MMKV, on the other hand, offers simpler and faster key-value storage with a more straightforward API for basic use cases.

13,842

A Cocoa / Objective-C wrapper around SQLite

Pros of FMDB

  • Built on top of SQLite, providing a familiar SQL interface
  • Supports complex queries and transactions
  • Well-established and widely used in iOS development

Cons of FMDB

  • Slower performance for simple key-value operations
  • Requires more setup and configuration compared to MMKV
  • Higher memory usage due to SQLite overhead

Code Comparison

FMDB (SQL-based):

FMDatabase *db = [FMDatabase databaseWithPath:@"myDB.sqlite"];
[db open];
[db executeUpdate:@"INSERT INTO users (name, age) VALUES (?, ?)", @"John", @25];
FMResultSet *result = [db executeQuery:@"SELECT * FROM users WHERE age > ?", @18];
[db close];

MMKV (Key-Value based):

MMKV *kv = [MMKV defaultMMKV];
[kv setObject:@"John" forKey:@"name"];
[kv setInt32:25 forKey:@"age"];
NSString *name = [kv getObjectOfClass:NSString.class forKey:@"name"];
int32_t age = [kv getInt32ForKey:@"age"];

FMDB is better suited for complex data structures and relationships, while MMKV excels in simple key-value storage with high performance. FMDB offers more flexibility in querying and data manipulation, but MMKV provides faster read/write operations for basic data storage needs.

A toolkit for SQLite databases, with a focus on application development

Pros of GRDB.swift

  • Full-featured SQLite wrapper with support for complex queries and migrations
  • Offers both raw SQL and Swift query interface for flexibility
  • Supports reactive programming with RxSwift and Combine

Cons of GRDB.swift

  • Larger footprint and potentially slower performance for simple key-value storage
  • Steeper learning curve due to more complex API and SQL knowledge requirements

Code Comparison

GRDB.swift:

try dbQueue.write { db in
    try Player(name: "Arthur", score: 100).insert(db)
}

let players = try dbQueue.read { db in
    try Player.filter(Column("score") > 80).fetchAll(db)
}

MMKV:

MMKV.default().set(100, forKey: "Arthur_score")

let score = MMKV.default().int64(forKey: "Arthur_score")

Summary

GRDB.swift is a comprehensive SQLite wrapper offering advanced database features, while MMKV is a lightweight key-value storage solution. GRDB.swift provides more flexibility for complex data structures and queries but may be overkill for simple storage needs. MMKV offers simplicity and high performance for basic key-value pairs but lacks advanced querying capabilities.

Simple Swift wrapper for Keychain that works on iOS, watchOS, tvOS and macOS.

Pros of KeychainAccess

  • Specifically designed for iOS Keychain, providing a more tailored solution for Apple platforms
  • Simple and intuitive API, making it easier to use for developers familiar with Swift
  • Supports synchronization across devices via iCloud Keychain

Cons of KeychainAccess

  • Limited to Apple platforms, lacking cross-platform support
  • May have lower performance compared to MMKV for large datasets or frequent read/write operations
  • Doesn't offer encryption beyond what's provided by the iOS Keychain

Code Comparison

KeychainAccess:

let keychain = Keychain(service: "com.example.app")
keychain["username"] = "john_doe"
let username = keychain["username"]

MMKV:

let mmkv = MMKV(mmapID: "myMMKV")
mmkv.set("john_doe", forKey: "username")
let username = mmkv.string(forKey: "username")

Both libraries offer simple key-value storage, but KeychainAccess is specifically designed for secure storage in the iOS Keychain, while MMKV provides a more general-purpose, high-performance storage solution. KeychainAccess is ideal for storing sensitive data on Apple platforms, whereas MMKV offers better performance and cross-platform support for general data storage needs.

The better way to deal with JSON data in Swift.

Pros of SwiftyJSON

  • Specifically designed for JSON parsing in Swift, offering a more intuitive API for Swift developers
  • Lightweight and easy to integrate into Swift projects
  • Provides type-safe access to JSON data with optional chaining

Cons of SwiftyJSON

  • Limited to JSON data format, while MMKV supports key-value storage for various data types
  • May have slower performance compared to MMKV for large datasets
  • Lacks built-in encryption and multi-process support

Code Comparison

SwiftyJSON:

let json = JSON(data: dataFromNetworking)
if let name = json["user"]["name"].string {
    // Do something with name
}

MMKV:

let mmkv = MMKV(mmapID: "myMMKV")
mmkv.set("John", forKey: "name")
let name = mmkv.string(forKey: "name")

SwiftyJSON focuses on JSON parsing with a Swift-friendly syntax, while MMKV provides a key-value storage solution with additional features like encryption and multi-process support. SwiftyJSON is ideal for projects primarily dealing with JSON data, whereas MMKV offers a more versatile storage solution for various data types and use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

license PRs Welcome Release Version Platform

中文版本请参看这里

MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application. It's currently available on Android, iOS/macOS, Windows, POSIX and HarmonyOS NEXT.

MMKV for Android

Features

  • Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of Android to achieve the best performance.

    • Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
  • Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no sync, no apply calls needed.

  • Small.

    • A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics, and nothing more. It's really tidy.
    • About 50K in binary size: MMKV adds about 50K per architecture on App size, and much less when zipped (APK).

Getting Started

Installation Via Maven

Add the following lines to build.gradle on your app module:

dependencies {
    implementation 'com.tencent:mmkv:1.3.9'
    // replace "1.3.9" with any available version
}

For other installation options, see Android Setup.

Quick Tutorial

You can use MMKV as you go. All changes are saved immediately, no sync, no apply calls needed.
Setup MMKV on App startup, say your Application class, add these lines:

public void onCreate() {
    super.onCreate();

    String rootDir = MMKV.initialize(this);
    System.out.println("mmkv root: " + rootDir);
    //……
}

MMKV has a global instance, that can be used directly:

import com.tencent.mmkv.MMKV;
    
MMKV kv = MMKV.defaultMMKV();

kv.encode("bool", true);
boolean bValue = kv.decodeBool("bool");

kv.encode("int", Integer.MIN_VALUE);
int iValue = kv.decodeInt("int");

kv.encode("string", "Hello from mmkv");
String str = kv.decodeString("string");

MMKV also supports Multi-Process Access. Full tutorials can be found here Android Tutorial.

Performance

Writing random int for 1000 times, we get this chart:

For more benchmark data, please refer to our benchmark.

MMKV for iOS/macOS

Features

  • Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of iOS/macOS to achieve the best performance.

  • Easy-to-use. You can use MMKV as you go, no configurations are needed. All changes are saved immediately, no synchronize calls are needed.

  • Small.

    • A handful of files: MMKV contains encode/decode helpers and mmap logics and nothing more. It's really tidy.
    • Less than 30K in binary size: MMKV adds less than 30K per architecture on App size, and much less when zipped (IPA).

Getting Started

Installation Via CocoaPods:

  1. Install CocoaPods;
  2. Open the terminal, cd to your project directory, run pod repo update to make CocoaPods aware of the latest available MMKV versions;
  3. Edit your Podfile, add pod 'MMKV' to your app target;
  4. Run pod install;
  5. Open the .xcworkspace file generated by CocoaPods;
  6. Add #import <MMKV/MMKV.h> to your source file and we are done.

For other installation options, see iOS/macOS Setup.

Quick Tutorial

You can use MMKV as you go, no configurations are needed. All changes are saved immediately, no synchronize calls are needed. Setup MMKV on App startup, in your -[MyApp application: didFinishLaunchingWithOptions:], add these lines:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // init MMKV in the main thread
    [MMKV initializeMMKV:nil];

    //...
    return YES;
}

MMKV has a global instance, that can be used directly:

MMKV *mmkv = [MMKV defaultMMKV];
    
[mmkv setBool:YES forKey:@"bool"];
BOOL bValue = [mmkv getBoolForKey:@"bool"];
    
[mmkv setInt32:-1024 forKey:@"int32"];
int32_t iValue = [mmkv getInt32ForKey:@"int32"];
    
[mmkv setString:@"hello, mmkv" forKey:@"string"];
NSString *str = [mmkv getStringForKey:@"string"];

MMKV also supports Multi-Process Access. Full tutorials can be found here.

Performance

Writing random int for 10000 times, we get this chart:

For more benchmark data, please refer to our benchmark.

MMKV for Windows

Features

  • Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of Windows to achieve the best performance.

    • Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
  • Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no save, no sync calls are needed.

  • Small.

    • A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics, and nothing more. It's really tidy.
    • About 10K in binary size: MMKV adds about 10K on application size, and much less when zipped.

Getting Started

Installation Via Source

  1. Getting source code from git repository:

    git clone https://github.com/Tencent/MMKV.git
    
  2. Add Core/core.vcxproj to your solution;

  3. Add MMKV project to your project's dependencies;

  4. Add $(OutDir)include to your project's C/C++ -> General -> Additional Include Directories;

  5. Add $(OutDir) to your project's Linker -> General -> Additional Library Directories;

  6. Add mmkv.lib to your project's Linker -> Input -> Additional Dependencies;

  7. Add #include <MMKV/MMKV.h> to your source file and we are done.

note:

  1. MMKV is compiled with MT/MTd runtime by default. If your project uses MD/MDd, you should change MMKV's setting to match your project's (C/C++ -> Code Generation -> Runtime Library), or vice versa.
  2. MMKV is developed with Visual Studio 2017, change the Platform Toolset if you use a different version of Visual Studio.

For other installation options, see Windows Setup.

Quick Tutorial

You can use MMKV as you go. All changes are saved immediately, no sync, no save calls needed.
Setup MMKV on App startup, say in your main(), add these lines:

#include <MMKV/MMKV.h>

int main() {
    std::wstring rootDir = getYourAppDocumentDir();
    MMKV::initializeMMKV(rootDir);
    //...
}

MMKV has a global instance, that can be used directly:

auto mmkv = MMKV::defaultMMKV();

mmkv->set(true, "bool");
std::cout << "bool = " << mmkv->getBool("bool") << std::endl;

mmkv->set(1024, "int32");
std::cout << "int32 = " << mmkv->getInt32("int32") << std::endl;

mmkv->set("Hello, MMKV for Windows", "string");
std::string result;
mmkv->getString("string", result);
std::cout << "string = " << result << std::endl;

MMKV also supports Multi-Process Access. Full tutorials can be found here Windows Tutorial.

MMKV for POSIX

Features

  • Efficient. MMKV uses mmap to keep memory synced with files, and protobuf to encode/decode values, making the most of POSIX to achieve the best performance.

    • Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
  • Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no save, no sync calls are needed.

  • Small.

    • A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics, and nothing more. It's really tidy.
    • About 7K in binary size: MMKV adds about 7K on application size, and much less when zipped.

Getting Started

Installation Via CMake

  1. Getting source code from the git repository:

    git clone https://github.com/Tencent/MMKV.git
    
  2. Edit your CMakeLists.txt, add those lines:

    add_subdirectory(mmkv/POSIX/src mmkv)
    target_link_libraries(MyApp
        mmkv)
    
  3. Add #include "MMKV.h" to your source file and we are done.

For other installation options, see POSIX Setup.

Quick Tutorial

You can use MMKV as you go. All changes are saved immediately, no sync, no save calls needed.
Setup MMKV on App startup, say in your main(), add these lines:

#include "MMKV.h"

int main() {
    std::string rootDir = getYourAppDocumentDir();
    MMKV::initializeMMKV(rootDir);
    //...
}

MMKV has a global instance, that can be used directly:

auto mmkv = MMKV::defaultMMKV();

mmkv->set(true, "bool");
std::cout << "bool = " << mmkv->getBool("bool") << std::endl;

mmkv->set(1024, "int32");
std::cout << "int32 = " << mmkv->getInt32("int32") << std::endl;

mmkv->set("Hello, MMKV for Windows", "string");
std::string result;
mmkv->getString("string", result);
std::cout << "string = " << result << std::endl;

MMKV also supports Multi-Process Access. Full tutorials can be found here POSIX Tutorial.

MMKV for HarmonyOS NEXT

Features

  • Efficient. MMKV uses mmap to keep memory synced with file, and protobuf to encode/decode values, making the most of native platform to achieve best performance.

    • Multi-Process concurrency: MMKV supports concurrent read-read and read-write access between processes.
  • Easy-to-use. You can use MMKV as you go. All changes are saved immediately, no sync, no flush calls needed.

  • Small.

    • A handful of files: MMKV contains process locks, encode/decode helpers and mmap logics and nothing more. It's really tidy.
    • About 600K in binary size: MMKV adds about 600K per architecture on App size, and much less when zipped (HAR/HAP).

Getting Started

Installation via OHPM:

ohpm install @tencent/mmkv

Quick Tutorial

You can use MMKV as you go. All changes are saved immediately, no sync, no apply calls needed.
Setup MMKV on App startup, say your EntryAbility.onCreate() function, add these lines:

import { MMKV } from '@tencent/mmkv';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    let appCtx = this.context.getApplicationContext();
    let mmkvRootDir = MMKV.initialize(appCtx);
    console.info('mmkv rootDir: ', mmkvRootDir);
    ……
  }

MMKV has a global instance, that can be used directly:

import { MMKV } from '@tencent/mmkv';
    
let mmkv = MMKV.defaultMMKV();
mmkv.encodeBool('bool', true);
console.info('bool = ', mmkv.decodeBool('bool'));
    
mmkv.encodeInt32('int32', Math.pow(2, 31) - 1);
console.info('max int32 = ', mmkv.decodeInt32('int32'));
    
mmkv.encodeInt64('int', BigInt(2**63) - BigInt(1));
console.info('max int64 = ', mmkv.decodeInt64('int'));
    
let str: string = 'Hello OpenHarmony from MMKV';
mmkv.encodeString('string', str);
console.info('string = ', mmkv.decodeString('string'));

let arrayBuffer: ArrayBuffer = StringToArrayBuffer('Hello OpenHarmony from MMKV with bytes');
mmkv.encodeBytes('bytes', arrayBuffer);
let bytes = mmkv.decodeBytes('bytes');
console.info('bytes = ', ArrayBufferToString(bytes));

As you can see, MMKV is quite easy to use. For the full documentation, see HarmonyOS NEXT Tutorial.

License

MMKV is published under the BSD 3-Clause license. For details check out the LICENSE.TXT.

Change Log

Check out the CHANGELOG.md for details of change history.

Contributing

If you are interested in contributing, check out the CONTRIBUTING.md, also join our Tencent OpenSource Plan.

To give clarity of what is expected of our members, MMKV has adopted the code of conduct defined by the Contributor Covenant, which is widely used. And we think it articulates our values well. For more, check out the Code of Conduct.

FAQ & Feedback

Check out the FAQ first. Should there be any questions, don't hesitate to create issues.

Personal Information Protection Rules

User privacy is taken very seriously: MMKV does not obtain, collect or upload any personal information. Please refer to the MMKV SDK Personal Information Protection Rules for details.