├── .gitignore
├── FastSharedPreferences
├── .gitignore
├── app
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ │ ├── androidTest
│ │ └── java
│ │ │ └── com
│ │ │ └── jeremy
│ │ │ └── fspdemo
│ │ │ └── FastSharedPreferencesAndroidTest.java
│ │ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ └── com
│ │ │ └── jeremy
│ │ │ └── fspdemo
│ │ │ ├── DemoApplication.java
│ │ │ ├── InterProcessService.java
│ │ │ ├── MainActivity.java
│ │ │ ├── bean
│ │ │ └── IPSData.java
│ │ │ └── benchmark
│ │ │ ├── BenchmarkActivity.java
│ │ │ ├── BenchmarkController.java
│ │ │ ├── BenchmarkManager.java
│ │ │ ├── BenchmarkResult.java
│ │ │ ├── IBenchmark.java
│ │ │ ├── RunTimer.java
│ │ │ └── SQLIteKV.java
│ │ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_benchmark.xml
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
├── build.gradle
├── fastsharedpreferences
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ │ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── jeremy
│ │ │ │ └── fastsharedpreferences
│ │ │ │ ├── EnhancedEditor.java
│ │ │ │ ├── EnhancedSharedPreferences.java
│ │ │ │ ├── FastSharedPreferences.java
│ │ │ │ └── io
│ │ │ │ ├── IoUtil.java
│ │ │ │ └── ReadWriteManager.java
│ │ └── res
│ │ │ └── values
│ │ │ └── strings.xml
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── jeremy
│ │ └── fastsharedpreferences
│ │ ├── FastSharedPreferencesTest.java
│ │ └── TestBean.java
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
├── LICENSE
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # Keystore files
46 | # Uncomment the following line if you do not want to check your keystore files in.
47 | #*.jks
48 |
49 | # External native build folder generated in Android Studio 2.2 and later
50 | .externalNativeBuild
51 |
52 | # Google Services (e.g. APIs or Firebase)
53 | google-services.json
54 |
55 | # Freeline
56 | freeline.py
57 | freeline/
58 | freeline_project_description.json
59 |
60 | # fastlane
61 | fastlane/report.xml
62 | fastlane/Preview.html
63 | fastlane/screenshots
64 | fastlane/test_output
65 | fastlane/readme.md
66 |
67 | release
68 | target
69 | build
70 | .settings
71 | .project
72 | .classpath
73 | .idea
74 | .DS_Store
75 | bin
76 | gen
77 | proguard
78 | .pmd
79 | *~
80 | *.iml
81 | tmp
82 | gen-external-apklibs
83 | out
84 | tmp
85 | coverage
86 | build/
87 | .gradle/
88 | local.properties
89 | .gradletasknamecache
90 | src/main/provided_libs
91 | src/main/assets/*.dex
92 | src/main/assets/mtdata*.json
93 | reports/
94 | aartojar/
95 | keystore
96 | captures
97 | repo/
98 |
--------------------------------------------------------------------------------
/FastSharedPreferences/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches/build_file_checksums.ser
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | .DS_Store
9 | /build
10 | /captures
11 | .externalNativeBuild
12 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 27
5 | defaultConfig {
6 | applicationId "com.jeremy.fastsharedpreferences"
7 | minSdkVersion 16
8 | targetSdkVersion 27
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(include: ['*.jar'], dir: 'libs')
23 | implementation 'com.android.support:appcompat-v7:27.1.1'
24 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
25 | testImplementation 'junit:junit:4.12'
26 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
27 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
28 |
29 | implementation group: 'com.tencent', name: 'mmkv', version: '1.0.12'
30 | implementation project(':fastsharedpreferences')
31 | }
32 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/androidTest/java/com/jeremy/fspdemo/FastSharedPreferencesAndroidTest.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.support.test.InstrumentationRegistry;
6 | import android.support.test.runner.AndroidJUnit4;
7 | import android.util.Log;
8 |
9 | import com.jeremy.fastsharedpreferences.FastSharedPreferences;
10 | import com.jeremy.fspdemo.bean.IPSData;
11 |
12 | import org.junit.Before;
13 | import org.junit.Ignore;
14 | import org.junit.Test;
15 | import org.junit.runner.RunWith;
16 |
17 | import static org.junit.Assert.assertEquals;
18 | import static org.junit.Assert.assertNotNull;
19 | import static org.junit.Assert.assertTrue;
20 | import static org.junit.Assert.fail;
21 |
22 | /**
23 | * Created by liaohailiang on 2018/10/24.
24 | */
25 | @RunWith(AndroidJUnit4.class)
26 | public class FastSharedPreferencesAndroidTest {
27 |
28 | private Context context;
29 |
30 | @Before
31 | public void setup() {
32 | context = InstrumentationRegistry.getTargetContext();
33 | FastSharedPreferences.init(context);
34 | }
35 |
36 | @Test
37 | public void testLoad() {
38 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_load");
39 | assertNotNull(sharedPreferences);
40 | }
41 |
42 | @Test
43 | public void testWriteString() {
44 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_string");
45 | sharedPreferences.edit().putString("test_key", "test_value").apply();
46 | sleep(100);
47 | sharedPreferences = FastSharedPreferences.get("test_write_string");
48 | assertEquals(sharedPreferences.getString("test_key", ""), "test_value");
49 | }
50 |
51 | @Test
52 | public void testWriteInteger() {
53 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_integer");
54 | sharedPreferences.edit().putInt("test_key", 100).apply();
55 | sleep(100);
56 | sharedPreferences = FastSharedPreferences.get("test_write_integer");
57 | assertEquals(sharedPreferences.getInt("test_key", -1), 100);
58 | }
59 |
60 | @Test
61 | public void testWriteLong() {
62 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_long");
63 | sharedPreferences.edit().putLong("test_key", 100).apply();
64 | sleep(100);
65 | sharedPreferences = FastSharedPreferences.get("test_write_long");
66 | assertEquals(sharedPreferences.getLong("test_key", -1), 100);
67 | }
68 |
69 | @Test
70 | public void testWriteFloat() {
71 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_float");
72 | sharedPreferences.edit().putFloat("test_key", 100.0f).apply();
73 | sleep(100);
74 | sharedPreferences = FastSharedPreferences.get("test_write_float");
75 | assertTrue(sharedPreferences.getFloat("test_key", -1) == 100.0f);
76 | }
77 |
78 | @Test
79 | public void testWriteBoolean() {
80 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_bool");
81 | sharedPreferences.edit().putBoolean("test_key", true).apply();
82 | sleep(100);
83 | sharedPreferences = FastSharedPreferences.get("test_write_bool");
84 | assertEquals(sharedPreferences.getBoolean("test_key", false), true);
85 | }
86 |
87 | @Test
88 | public void testWriteIntegers() {
89 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_int");
90 | for (int i = 0; i < 1000; i++) {
91 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
92 | }
93 | sleep(200);
94 | sharedPreferences = FastSharedPreferences.get("test_write_int");
95 | for (int i = 0; i < 1000; i++) {
96 | assertEquals(sharedPreferences.getInt("test_key_" + i, -1), i);
97 | }
98 | }
99 |
100 | @Test
101 | public void testWriteCount() {
102 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_count");
103 | sharedPreferences.edit().clear().commit();
104 | sleep(200);
105 | for (int i = 0; i < 10000; i++) {
106 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
107 | }
108 | sleep(1500);
109 | sharedPreferences = FastSharedPreferences.get("test_write_count");
110 | int size = sharedPreferences.getAll().size();
111 | assertEquals(size, 10000);
112 | }
113 |
114 | @Test
115 | public void testRemove() {
116 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_re");
117 | sharedPreferences.edit().putString("test_key", "test_value").apply();
118 | sleep(100);
119 | sharedPreferences.edit().remove("test_key").apply();
120 | sleep(100);
121 | sharedPreferences = FastSharedPreferences.get("test_write_re");
122 | assertEquals(sharedPreferences.contains("test_key"), false);
123 | }
124 |
125 | @Test
126 | public void testClear() {
127 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_cl");
128 | for (int i = 0; i < 1000; i++) {
129 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
130 | }
131 | sleep(200);
132 | sharedPreferences.edit().clear().apply();
133 | sleep(100);
134 | sharedPreferences = FastSharedPreferences.get("test_write_cl");
135 | assertEquals(sharedPreferences.getAll().size(), 0);
136 | }
137 |
138 | @Test
139 | public void testInterProcessWriteInteger() {
140 | IPSData data = new IPSData("ip_test_write_integer", "test_key", 100);
141 | Intent intent = new Intent(context, InterProcessService.class);
142 | intent.putExtra(InterProcessService.EXTRA_KEY, data);
143 | context.startService(intent);
144 | sleep(500);
145 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("ip_test_write_integer");
146 | assertEquals(sharedPreferences.getInt("test_key", -1), 100);
147 | }
148 |
149 | @Test
150 | public void testInterProcessWriteInteger1() {
151 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("ip_test_write_integer_1");
152 | sharedPreferences.edit().putInt("test_key", 100).apply();
153 | assertEquals(sharedPreferences.getInt("test_key", -1), 100);
154 | IPSData data = new IPSData("ip_test_write_integer_1", "test_key", 200);
155 | Intent intent = new Intent(context, InterProcessService.class);
156 | intent.putExtra(InterProcessService.EXTRA_KEY, data);
157 | context.startService(intent);
158 | sleep(500);
159 | assertEquals(sharedPreferences.getInt("test_key", -1), 200);
160 | }
161 |
162 | @Test
163 | public void testInterProcessWriteInteger2() {
164 | final String name = "ip_test_write_integer_2";
165 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(name);
166 | Log.d("testInterProcessWriteInteger2", "size: " + sharedPreferences.getAll().size());
167 | sharedPreferences.edit().clear().apply();
168 | sleep(200);
169 | final int loop = 10;
170 | for (int i = 0; i < loop; i++) {
171 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
172 | }
173 | sleep(1000);
174 | for (int i = 0; i < loop; i++) {
175 | int remoteIndex = loop + i;
176 | IPSData data = new IPSData(name, "test_key_" + remoteIndex, remoteIndex);
177 | Intent intent = new Intent(context, InterProcessService.class);
178 | intent.putExtra(InterProcessService.EXTRA_KEY, data);
179 | context.startService(intent);
180 | }
181 | sleep(1500);
182 | for (int i = 0; i < loop * 2; i++) {
183 | assertEquals(sharedPreferences.getInt("test_key_" + i, -1), i);
184 | }
185 | }
186 |
187 | private void sleep(long time) {
188 | try {
189 | Thread.sleep(time);
190 | } catch (Exception e) {
191 | }
192 | }
193 | }
194 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/DemoApplication.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo;
2 |
3 | import android.app.Application;
4 |
5 | import com.jeremy.fastsharedpreferences.FastSharedPreferences;
6 | import com.jeremy.fspdemo.benchmark.BenchmarkManager;
7 |
8 | /**
9 | * Created by liaohailiang on 2018/10/24.
10 | */
11 | public class DemoApplication extends Application {
12 |
13 | @Override
14 | public void onCreate() {
15 | super.onCreate();
16 | FastSharedPreferences.init(this);
17 | BenchmarkManager.getManager().init(this);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/InterProcessService.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo;
2 |
3 | import android.app.Service;
4 | import android.content.Intent;
5 | import android.os.IBinder;
6 | import android.support.annotation.Nullable;
7 |
8 | import com.jeremy.fastsharedpreferences.FastSharedPreferences;
9 | import com.jeremy.fspdemo.bean.IPSData;
10 |
11 | /**
12 | * Created by liaohailiang on 2019/1/18.
13 | */
14 | public class InterProcessService extends Service {
15 |
16 | public static final String EXTRA_KEY = "extra_key";
17 |
18 | @Nullable
19 | @Override
20 | public IBinder onBind(Intent intent) {
21 | return null;
22 | }
23 |
24 | @Override
25 | public void onCreate() {
26 | super.onCreate();
27 | }
28 |
29 | @Override
30 | public void onDestroy() {
31 | super.onDestroy();
32 | }
33 |
34 | @Override
35 | public int onStartCommand(Intent intent, int flags, int startId) {
36 | IPSData data = (IPSData) intent.getSerializableExtra(EXTRA_KEY);
37 | if (data == null) {
38 | return super.onStartCommand(intent, flags, startId);
39 | }
40 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(data.name);
41 | if (data.value instanceof Integer) {
42 | sharedPreferences.edit().putInt(data.key, (int) data.value).apply();
43 | } else if (data.value instanceof String) {
44 | sharedPreferences.edit().putString(data.key, (String) data.value).apply();
45 | } else if (data.value instanceof Long) {
46 | sharedPreferences.edit().putLong(data.key, (long) data.value).apply();
47 | } else if (data.value instanceof Float) {
48 | sharedPreferences.edit().putFloat(data.key, (float) data.value).apply();
49 | } else if (data.value instanceof Boolean) {
50 | sharedPreferences.edit().putBoolean(data.key, (boolean) data.value).apply();
51 | }
52 | return super.onStartCommand(intent, flags, startId);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 | import android.widget.Toast;
8 |
9 | import com.jeremy.fastsharedpreferences.FastSharedPreferences;
10 | import com.jeremy.fspdemo.bean.IPSData;
11 | import com.jeremy.fspdemo.benchmark.BenchmarkActivity;
12 |
13 | public class MainActivity extends AppCompatActivity {
14 |
15 | private static final String FSP_ID = "test";
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_main);
21 | }
22 |
23 | public void toBenchmark(View v) {
24 | startActivity(new Intent(this, BenchmarkActivity.class));
25 | }
26 |
27 | public void writeInt(View v) {
28 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(FSP_ID);
29 | sharedPreferences.edit().putInt("test_key", 100).apply();
30 | Toast.makeText(this, "Write Int", Toast.LENGTH_SHORT).show();
31 | }
32 |
33 | public void readInt(View v) {
34 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(FSP_ID);
35 | int ret = sharedPreferences.getInt("test_key", -1);
36 | Toast.makeText(this, "Read Int: " + ret, Toast.LENGTH_SHORT).show();
37 | }
38 |
39 | public void interProcessWrite(View v) {
40 | IPSData data = new IPSData(FSP_ID, "test_key", 200);
41 | Intent intent = new Intent(this, InterProcessService.class);
42 | intent.putExtra(InterProcessService.EXTRA_KEY, data);
43 | startService(intent);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/bean/IPSData.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.bean;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * Created by liaohailiang on 2019/1/18.
7 | */
8 | public class IPSData implements Serializable {
9 | public String name;
10 | public String key;
11 | public Object value;
12 |
13 | public IPSData(String name, String key, Object value) {
14 | this.name = name;
15 | this.key = key;
16 | this.value = value;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/BenchmarkActivity.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.util.Log;
6 | import android.view.View;
7 | import android.widget.Toast;
8 |
9 | import com.jeremy.fspdemo.R;
10 |
11 | import java.util.List;
12 |
13 | public class BenchmarkActivity extends AppCompatActivity {
14 |
15 | private static final String TAG = "BENCHMARK";
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_benchmark);
21 | }
22 |
23 | public void batchWriteInt(View v) {
24 | Toast.makeText(this, "Start benchmark", Toast.LENGTH_SHORT).show();
25 | new Thread(new Runnable() {
26 | @Override
27 | public void run() {
28 | List results = BenchmarkManager.getManager().benchmarkWriteInt();
29 | final String result = results.toString();
30 | Log.d(TAG, result);
31 | runOnUiThread(new Runnable() {
32 | @Override
33 | public void run() {
34 | Toast.makeText(BenchmarkActivity.this, result, Toast.LENGTH_LONG).show();
35 | }
36 | });
37 | }
38 | }).start();
39 | }
40 |
41 | public void batchReadInt(View v) {
42 | Toast.makeText(this, "Start benchmark", Toast.LENGTH_SHORT).show();
43 | new Thread(new Runnable() {
44 | @Override
45 | public void run() {
46 | List results = BenchmarkManager.getManager().benchmarkReadInt();
47 | final String result = results.toString();
48 | Log.d(TAG, result);
49 | runOnUiThread(new Runnable() {
50 | @Override
51 | public void run() {
52 | Toast.makeText(BenchmarkActivity.this, result, Toast.LENGTH_LONG).show();
53 | }
54 | });
55 | }
56 | }).start();
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/BenchmarkController.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by liaohailiang on 2018/11/8.
8 | */
9 | public class BenchmarkController {
10 |
11 | private List results = new ArrayList<>();
12 |
13 | public double runBenchmark(int count, IBenchmark benchmark) {
14 | results.clear();
15 | for (int i = 0; i < count; i++) {
16 | results.add(benchmark.benchmark());
17 | }
18 | return calculateAverage(results);
19 | }
20 |
21 | private double calculateAverage(List marks) {
22 | Long sum = 0L;
23 | if (!marks.isEmpty()) {
24 | for (Long mark : marks) {
25 | sum += mark;
26 | }
27 | return sum.doubleValue() / marks.size();
28 | }
29 | return sum;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/BenchmarkManager.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | import com.jeremy.fastsharedpreferences.FastSharedPreferences;
7 | import com.tencent.mmkv.MMKV;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import java.util.Random;
12 |
13 | /**
14 | * Created by liaohailiang on 2018/11/8.
15 | */
16 | public final class BenchmarkManager {
17 |
18 | private static final int LOOPS = 1000;
19 | private static final String SP_ID = "benchmark_sp";
20 | private static final String FSP_ID = "benchmark_fsp";
21 | private static final String MMKV_ID = "benchmark_mmkv";
22 |
23 | private static final String BATCH_WRITE_INT = "BatchWriteInt";
24 | private static final String BATCH_READ_INT = "BatchReadInt";
25 |
26 | private static class SingletonHolder {
27 | private static final BenchmarkManager SINGLETON = new BenchmarkManager();
28 | }
29 |
30 | public static BenchmarkManager getManager() {
31 | return SingletonHolder.SINGLETON;
32 | }
33 |
34 | private Context context;
35 |
36 | private BenchmarkManager() {
37 | }
38 |
39 | public void init(Context context) {
40 | this.context = context.getApplicationContext();
41 | MMKV.initialize(this.context);
42 | }
43 |
44 | public List benchmarkWriteInt() {
45 | BenchmarkController controller = new BenchmarkController();
46 | List results = new ArrayList<>();
47 | double benchmark = 0;
48 | benchmark = controller.runBenchmark(5, new IBenchmark() {
49 | @Override
50 | public long benchmark() {
51 | return spBatchWriteInt();
52 | }
53 | });
54 | results.add(new BenchmarkResult("SharedPreferences", BATCH_WRITE_INT, benchmark));
55 | benchmark = controller.runBenchmark(5, new IBenchmark() {
56 | @Override
57 | public long benchmark() {
58 | return sqliteWriteInt();
59 | }
60 | });
61 | results.add(new BenchmarkResult("SQLite", BATCH_WRITE_INT, benchmark));
62 | benchmark = controller.runBenchmark(200, new IBenchmark() {
63 | @Override
64 | public long benchmark() {
65 | return mmkvBatchWriteInt();
66 | }
67 | });
68 | results.add(new BenchmarkResult("MMKV", BATCH_WRITE_INT, benchmark));
69 | benchmark = controller.runBenchmark(200, new IBenchmark() {
70 | @Override
71 | public long benchmark() {
72 | return fspBatchWriteInt();
73 | }
74 | });
75 | results.add(new BenchmarkResult("FastSharedPreferences", BATCH_WRITE_INT, benchmark));
76 | return results;
77 | }
78 |
79 | public List benchmarkReadInt() {
80 | BenchmarkController controller = new BenchmarkController();
81 | List results = new ArrayList<>();
82 | double benchmark = 0;
83 | benchmark = controller.runBenchmark(5, new IBenchmark() {
84 | @Override
85 | public long benchmark() {
86 | return spBatchReadInt();
87 | }
88 | });
89 | results.add(new BenchmarkResult("SharedPreferences", BATCH_READ_INT, benchmark));
90 | benchmark = controller.runBenchmark(5, new IBenchmark() {
91 | @Override
92 | public long benchmark() {
93 | return sqliteBatchReadInt();
94 | }
95 | });
96 | results.add(new BenchmarkResult("SQLite", BATCH_READ_INT, benchmark));
97 | benchmark = controller.runBenchmark(200, new IBenchmark() {
98 | @Override
99 | public long benchmark() {
100 | return mmkvBatchReadInt();
101 | }
102 | });
103 | results.add(new BenchmarkResult("MMKV", BATCH_READ_INT, benchmark));
104 | benchmark = controller.runBenchmark(200, new IBenchmark() {
105 | @Override
106 | public long benchmark() {
107 | return fspBatchReadInt();
108 | }
109 | });
110 | results.add(new BenchmarkResult("FastSharedPreferences", BATCH_READ_INT, benchmark));
111 | return results;
112 | }
113 |
114 | private long spBatchWriteInt() {
115 | RunTimer.start();
116 | Random rand = new Random();
117 | SharedPreferences sharedPreferences = context.getSharedPreferences(SP_ID, 0);
118 | SharedPreferences.Editor editor = sharedPreferences.edit();
119 | for (int i = 0; i < LOOPS; i++) {
120 | String key = i + "";
121 | int value = rand.nextInt();
122 | editor.putInt(key, value);
123 | editor.apply();
124 | }
125 | long cost = RunTimer.end();
126 | return cost;
127 | }
128 |
129 | private long fspBatchWriteInt() {
130 | RunTimer.start();
131 | Random rand = new Random();
132 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(FSP_ID);
133 | SharedPreferences.Editor editor = sharedPreferences.edit();
134 | for (int i = 0; i < LOOPS; i++) {
135 | String key = i + "";
136 | int value = rand.nextInt();
137 | editor.putInt(key, value);
138 | editor.apply();
139 | }
140 | long cost = RunTimer.end();
141 | return cost;
142 | }
143 |
144 | private long sqliteWriteInt() {
145 | RunTimer.start();
146 | Random rand = new Random();
147 | SQLIteKV sqlIteKV = new SQLIteKV(context);
148 | for (int i = 0; i < LOOPS; i++) {
149 | String key = i + "";
150 | int value = rand.nextInt();
151 | sqlIteKV.putInt(key, value);
152 | }
153 | long cost = RunTimer.end();
154 | return cost;
155 | }
156 |
157 | private long mmkvBatchWriteInt() {
158 | RunTimer.start();
159 | Random rand = new Random();
160 | MMKV mmkv = MMKV.mmkvWithID(MMKV_ID, MMKV.SINGLE_PROCESS_MODE, null);
161 | for (int i = 0; i < LOOPS; i++) {
162 | String key = i + "";
163 | int value = rand.nextInt();
164 | mmkv.encode(key, value);
165 | }
166 | long cost = RunTimer.end();
167 | return cost;
168 | }
169 |
170 | private long spBatchReadInt() {
171 | RunTimer.start();
172 | SharedPreferences sharedPreferences = context.getSharedPreferences(SP_ID, 0);
173 | for (int i = 0; i < LOOPS; i++) {
174 | String key = i + "";
175 | int tmp = sharedPreferences.getInt(key, -1);
176 | }
177 | long cost = RunTimer.end();
178 | return cost;
179 | }
180 |
181 | private long fspBatchReadInt() {
182 | RunTimer.start();
183 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(FSP_ID);
184 | for (int i = 0; i < LOOPS; i++) {
185 | String key = i + "";
186 | int tmp = sharedPreferences.getInt(key, -1);
187 | }
188 | long cost = RunTimer.end();
189 | return cost;
190 | }
191 |
192 | private long sqliteBatchReadInt() {
193 | RunTimer.start();
194 | SQLIteKV sqlIteKV = new SQLIteKV(context);
195 | for (int i = 0; i < LOOPS; i++) {
196 | String key = i + "";
197 | int tmp = sqlIteKV.getInt(key);
198 | }
199 | long cost = RunTimer.end();
200 | return cost;
201 | }
202 |
203 | private long mmkvBatchReadInt() {
204 | RunTimer.start();
205 | MMKV mmkv = MMKV.mmkvWithID(MMKV_ID, MMKV.SINGLE_PROCESS_MODE, null);
206 | for (int i = 0; i < LOOPS; i++) {
207 | String key = i + "";
208 | int tmp = mmkv.getInt(key, -1);
209 | }
210 | long cost = RunTimer.end();
211 | return cost;
212 | }
213 | }
214 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/BenchmarkResult.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | /**
4 | * Created by liaohailiang on 2018/11/8.
5 | */
6 | public class BenchmarkResult {
7 |
8 | private String method;
9 | private String category;
10 | private double result;
11 |
12 | public BenchmarkResult(String method, String category, double result) {
13 | this.method = method;
14 | this.category = category;
15 | this.result = result;
16 | }
17 |
18 | public String getMethod() {
19 | return method;
20 | }
21 |
22 | public void setMethod(String method) {
23 | this.method = method;
24 | }
25 |
26 | public String getCategory() {
27 | return category;
28 | }
29 |
30 | public void setCategory(String category) {
31 | this.category = category;
32 | }
33 |
34 | public double getResult() {
35 | return result;
36 | }
37 |
38 | public void setResult(long result) {
39 | this.result = result;
40 | }
41 |
42 | @Override
43 | public String toString() {
44 | StringBuilder sb = new StringBuilder();
45 | sb.append("method: ").append(method).append(" | ")
46 | .append("category: ").append(category).append(" | ")
47 | .append("result: ").append(result);
48 | return sb.toString();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/IBenchmark.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | /**
4 | * Created by liaohailiang on 2018/11/8.
5 | */
6 | public interface IBenchmark {
7 |
8 | long benchmark();
9 | }
10 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/RunTimer.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | /**
4 | * Created by liaohailiang on 2018/10/23.
5 | */
6 | public class RunTimer {
7 |
8 | private static long startTime = -1;
9 |
10 | public static void start() {
11 | startTime = System.currentTimeMillis();
12 | }
13 |
14 | public static long end() {
15 | return System.currentTimeMillis() - startTime;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark/SQLIteKV.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fspdemo.benchmark;
2 |
3 | import android.content.ContentValues;
4 | import android.content.Context;
5 | import android.database.Cursor;
6 | import android.database.sqlite.SQLiteDatabase;
7 | import android.database.sqlite.SQLiteOpenHelper;
8 |
9 | public final class SQLIteKV {
10 | private static class SQLIteKVDBHelper extends SQLiteOpenHelper {
11 | private static final int DB_VERSION = 1;
12 | private static final String DB_NAME = "kv.db";
13 | public static final String TABLE_NAME_STR = "kv_str";
14 | public static final String TABLE_NAME_INT = "kv_int";
15 |
16 | public SQLIteKVDBHelper(Context context) {
17 | super(context, DB_NAME, null, DB_VERSION);
18 | }
19 |
20 | @Override
21 | public void onCreate(SQLiteDatabase sqLiteDatabase) {
22 | String sql = "create table if not exists " + TABLE_NAME_STR +
23 | " (k text UNIQUE on conflict replace, v text)";
24 | sqLiteDatabase.execSQL(sql);
25 | sql = "create table if not exists " + TABLE_NAME_INT +
26 | " (k text UNIQUE on conflict replace, v integer)";
27 | sqLiteDatabase.execSQL(sql);
28 | }
29 |
30 | @Override
31 | public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
32 | String sql = "DROP TABLE IF EXISTS " + TABLE_NAME_STR;
33 | sqLiteDatabase.execSQL(sql);
34 | sql = "DROP TABLE IF EXISTS " + TABLE_NAME_INT;
35 | sqLiteDatabase.execSQL(sql);
36 | onCreate(sqLiteDatabase);
37 | }
38 | }
39 | private SQLIteKVDBHelper m_dbHelper;
40 | private SQLiteDatabase m_writetableDB;
41 | private SQLiteDatabase m_readableDB;
42 |
43 | public SQLIteKV(Context context) {
44 | m_dbHelper = new SQLIteKVDBHelper(context);
45 | m_dbHelper.setWriteAheadLoggingEnabled(true);
46 | }
47 |
48 | public void beginTransaction() {
49 | getWritetableDB().beginTransaction();
50 | }
51 |
52 | public void endTransaction() {
53 | if (m_writetableDB != null) {
54 | try {
55 | m_writetableDB.setTransactionSuccessful();
56 | } finally {
57 | m_writetableDB.endTransaction();
58 | }
59 | }
60 | }
61 |
62 | private SQLiteDatabase getWritetableDB() {
63 | if (m_writetableDB == null) {
64 | m_writetableDB = m_dbHelper.getWritableDatabase();
65 | }
66 | return m_writetableDB;
67 | }
68 |
69 | private SQLiteDatabase getReadableDatabase() {
70 | if (m_readableDB == null) {
71 | m_readableDB = m_dbHelper.getReadableDatabase();
72 | }
73 | return m_readableDB;
74 | }
75 |
76 | @Override
77 | protected void finalize() throws Throwable {
78 | if (m_readableDB != null) {
79 | m_readableDB.close();
80 | }
81 | if (m_writetableDB != null) {
82 | m_writetableDB.close();
83 | }
84 | super.finalize();
85 | }
86 |
87 | public boolean putInt(String key, int value) {
88 | ContentValues contentValues = new ContentValues();
89 | contentValues.put("k", key);
90 | contentValues.put("v", value);
91 | long rowID = getWritetableDB().insert(SQLIteKVDBHelper.TABLE_NAME_INT, null, contentValues);
92 | return rowID != -1;
93 | }
94 |
95 | public int getInt(String key) {
96 | int value = 0;
97 | Cursor cursor = getReadableDatabase().rawQuery(
98 | "select v from " + SQLIteKVDBHelper.TABLE_NAME_INT + " where k=?", new String[] {key});
99 | if (cursor.moveToFirst()) {
100 | value = cursor.getInt(cursor.getColumnIndex("v"));
101 | }
102 | cursor.close();
103 | return value;
104 | }
105 |
106 | public boolean putString(String key, String value) {
107 | ContentValues contentValues = new ContentValues();
108 | contentValues.put("k", key);
109 | contentValues.put("v", value);
110 | long rowID = getWritetableDB().insert(SQLIteKVDBHelper.TABLE_NAME_STR, null, contentValues);
111 | return rowID != -1;
112 | }
113 |
114 | public String getString(String key) {
115 | String value = null;
116 | Cursor cursor = getReadableDatabase().rawQuery(
117 | "select v from " + SQLIteKVDBHelper.TABLE_NAME_STR + " where k=?", new String[] {key});
118 | if (cursor.moveToFirst()) {
119 | value = cursor.getString(cursor.getColumnIndex("v"));
120 | }
121 | cursor.close();
122 | return value;
123 | }
124 | }
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/layout/activity_benchmark.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
16 |
17 |
22 |
23 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
16 |
17 |
22 |
23 |
28 |
29 |
34 |
35 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | FastSharedPreferences
3 |
4 |
--------------------------------------------------------------------------------
/FastSharedPreferences/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/FastSharedPreferences/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | repositories {
6 | google()
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.1.2'
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | google()
19 | jcenter()
20 | }
21 | }
22 |
23 | task clean(type: Delete) {
24 | delete rootProject.buildDir
25 | }
26 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 27
5 |
6 | defaultConfig {
7 | minSdkVersion 15
8 | targetSdkVersion 27
9 | versionCode 1
10 | versionName "1.0"
11 |
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 |
22 | testOptions {
23 | unitTests.returnDefaultValues = true
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 |
30 | implementation 'com.android.support:appcompat-v7:27.1.1'
31 |
32 | testImplementation 'junit:junit:4.12'
33 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
34 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
35 |
36 | testImplementation 'org.mockito:mockito-core:2.8.9'
37 | testImplementation "org.powermock:powermock-module-junit4:1.7.3"
38 | testImplementation "org.powermock:powermock-module-junit4-rule:1.7.3"
39 | testImplementation "org.powermock:powermock-api-mockito2:1.7.3"
40 | testImplementation "org.powermock:powermock-classloading-xstream:1.7.3"
41 | }
42 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/java/com/jeremy/fastsharedpreferences/EnhancedEditor.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences;
2 |
3 | import android.content.SharedPreferences;
4 | import android.support.annotation.Nullable;
5 |
6 | import java.io.Serializable;
7 |
8 | /**
9 | * Created by liaohailiang on 2018/10/25.
10 | */
11 | public interface EnhancedEditor extends SharedPreferences.Editor {
12 |
13 | EnhancedEditor putSerializable(String key, @Nullable Serializable value);
14 | }
15 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/java/com/jeremy/fastsharedpreferences/EnhancedSharedPreferences.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences;
2 |
3 | import android.content.SharedPreferences;
4 | import android.support.annotation.Nullable;
5 |
6 | import java.io.Serializable;
7 |
8 | /**
9 | * Created by liaohailiang on 2018/10/25.
10 | */
11 | public interface EnhancedSharedPreferences extends SharedPreferences {
12 |
13 | Serializable getSerializable(String key, @Nullable Serializable defValue);
14 | }
15 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/java/com/jeremy/fastsharedpreferences/FastSharedPreferences.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences;
2 |
3 | import android.content.Context;
4 | import android.os.FileObserver;
5 | import android.support.annotation.Nullable;
6 | import android.support.v4.util.LruCache;
7 | import android.util.Log;
8 |
9 | import com.jeremy.fastsharedpreferences.io.ReadWriteManager;
10 |
11 | import java.io.File;
12 | import java.io.Serializable;
13 | import java.util.HashMap;
14 | import java.util.Map;
15 | import java.util.Set;
16 | import java.util.concurrent.ConcurrentHashMap;
17 | import java.util.concurrent.ExecutorService;
18 | import java.util.concurrent.Executors;
19 | import java.util.concurrent.atomic.AtomicBoolean;
20 | import java.util.concurrent.locks.ReadWriteLock;
21 | import java.util.concurrent.locks.ReentrantReadWriteLock;
22 |
23 | /**
24 | * Created by liaohailiang on 2018/10/23.
25 | */
26 | public class FastSharedPreferences implements EnhancedSharedPreferences {
27 |
28 | private static final String TAG = "FastSharedPreferences";
29 | // private static final Map FSP_CACHE = new HashMap<>();
30 | private static final FspCache FSP_CACHE = new FspCache();
31 | // private static final ExecutorService SYNC_EXECUTOR = Executors.newSingleThreadExecutor();
32 | private static final ExecutorService SYNC_EXECUTOR = Executors.newFixedThreadPool(4);
33 | private static Context sContext = null;
34 |
35 | public static void init(Context context) {
36 | if (context == null) {
37 | return;
38 | }
39 | sContext = context.getApplicationContext();
40 | }
41 |
42 | public static void setMaxSize(int maxSize) {
43 | FSP_CACHE.resize(maxSize);
44 | }
45 |
46 | public static FastSharedPreferences get(String name) {
47 | if (name == null || name.length() == 0) {
48 | return null;
49 | }
50 | synchronized (FastSharedPreferences.class) {
51 | return FSP_CACHE.get(name);
52 | }
53 | }
54 |
55 | private final String name;
56 | private final Map keyValueMap;
57 | private final FspEditor editor = new FspEditor();
58 | private final AtomicBoolean needSync = new AtomicBoolean(false);
59 | private final AtomicBoolean syncing = new AtomicBoolean(false);
60 | //这个锁主要是为了锁住拷贝数据的过程,当进行数据拷贝的时候,不允许任何写入操作
61 | private final ReadWriteLock copyLock = new ReentrantReadWriteLock();
62 | private final DataChangeObserver observer;
63 |
64 | private FastSharedPreferences(String name) {
65 | this.name = name;
66 | this.keyValueMap = new ConcurrentHashMap<>();
67 | reload();
68 | observer = new DataChangeObserver(ReadWriteManager.getFilePath(sContext, name));
69 | observer.startWatching();
70 | }
71 |
72 | @Override
73 | public Map getAll() {
74 | return keyValueMap;
75 | }
76 |
77 | @Nullable
78 | @Override
79 | public String getString(String s, @Nullable String s1) {
80 | if (keyValueMap.containsKey(s)) {
81 | return (String) keyValueMap.get(s);
82 | }
83 | return s1;
84 | }
85 |
86 | @Override
87 | public Serializable getSerializable(String key, @Nullable Serializable defValue) {
88 | if (keyValueMap.containsKey(key)) {
89 | return (Serializable) keyValueMap.get(key);
90 | }
91 | return defValue;
92 | }
93 |
94 | @Nullable
95 | @Override
96 | public Set getStringSet(String s, @Nullable Set set) {
97 | if (keyValueMap.containsKey(s)) {
98 | return (Set) keyValueMap.get(s);
99 | }
100 | return set;
101 | }
102 |
103 | @Override
104 | public int getInt(String s, int i) {
105 | if (keyValueMap.containsKey(s)) {
106 | return (int) keyValueMap.get(s);
107 | }
108 | return i;
109 | }
110 |
111 | @Override
112 | public long getLong(String s, long l) {
113 | if (keyValueMap.containsKey(s)) {
114 | return (long) keyValueMap.get(s);
115 | }
116 | return l;
117 | }
118 |
119 | @Override
120 | public float getFloat(String s, float v) {
121 | if (keyValueMap.containsKey(s)) {
122 | return (float) keyValueMap.get(s);
123 | }
124 | return v;
125 | }
126 |
127 | @Override
128 | public boolean getBoolean(String s, boolean b) {
129 | if (keyValueMap.containsKey(s)) {
130 | return (boolean) keyValueMap.get(s);
131 | }
132 | return b;
133 | }
134 |
135 | @Override
136 | public boolean contains(String s) {
137 | return keyValueMap.containsKey(s);
138 | }
139 |
140 | @Override
141 | public EnhancedEditor edit() {
142 | return editor;
143 | }
144 |
145 | @Override
146 | public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
147 |
148 | }
149 |
150 | @Override
151 | public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
152 |
153 | }
154 |
155 | private void reload() {
156 | Log.d(TAG, "reload data");
157 | Object loadedData = new ReadWriteManager(sContext, name).read();
158 | this.keyValueMap.clear();
159 | if (loadedData != null) {
160 | this.keyValueMap.putAll((Map extends String, ?>) loadedData);
161 | }
162 | }
163 |
164 | private int sizeOf() {
165 | File file = new File(ReadWriteManager.getFilePath(sContext, name));
166 | if (!file.exists()) {
167 | return 0;
168 | }
169 | return (int) (file.length() / 1024);
170 | }
171 |
172 | private class FspEditor implements EnhancedEditor {
173 | @Override
174 | public EnhancedEditor putSerializable(String key, @Nullable Serializable value) {
175 | put(key, value);
176 | return this;
177 | }
178 |
179 | @Override
180 | public EnhancedEditor putString(String s, @Nullable String s1) {
181 | put(s, s1);
182 | return this;
183 | }
184 |
185 | @Override
186 | public EnhancedEditor putStringSet(String s, @Nullable Set set) {
187 | put(s, set);
188 | return this;
189 | }
190 |
191 | @Override
192 | public EnhancedEditor putInt(String s, int i) {
193 | put(s, i);
194 | return this;
195 | }
196 |
197 | @Override
198 | public EnhancedEditor putLong(String s, long l) {
199 | put(s, l);
200 | return this;
201 | }
202 |
203 | @Override
204 | public EnhancedEditor putFloat(String s, float v) {
205 | put(s, v);
206 | return this;
207 | }
208 |
209 | @Override
210 | public EnhancedEditor putBoolean(String s, boolean b) {
211 | put(s, b);
212 | return this;
213 | }
214 |
215 | private void put(String s, Object obj) {
216 | copyLock.readLock().lock();
217 | keyValueMap.put(s, obj);
218 | copyLock.readLock().unlock();
219 | }
220 |
221 | @Override
222 | public Editor remove(String s) {
223 | copyLock.readLock().lock();
224 | keyValueMap.remove(s);
225 | copyLock.readLock().unlock();
226 | return this;
227 | }
228 |
229 | @Override
230 | public EnhancedEditor clear() {
231 | copyLock.readLock().lock();
232 | keyValueMap.clear();
233 | copyLock.readLock().unlock();
234 | return this;
235 | }
236 |
237 | @Override
238 | public boolean commit() {
239 | sync();
240 | return true;
241 | }
242 |
243 | @Override
244 | public void apply() {
245 | sync();
246 | }
247 |
248 | private void sync() {
249 | needSync.compareAndSet(false, true);
250 | postSyncTask();
251 | }
252 |
253 | private synchronized void postSyncTask() {
254 | if (syncing.get()) {
255 | return;
256 | }
257 | SYNC_EXECUTOR.execute(new SyncTask());
258 | }
259 |
260 | private class SyncTask implements Runnable {
261 |
262 | @Override
263 | public void run() {
264 | if (!needSync.get()) {
265 | return;
266 | }
267 | //先把syncing标记置为true
268 | syncing.compareAndSet(false, true);
269 | //copy map,copy的过程中不允许写入
270 | copyLock.writeLock().lock();
271 | Map storeMap = new HashMap<>(keyValueMap);
272 | copyLock.writeLock().unlock();
273 | // Log.d("FastSharedPreferences", "start sync with item size: " + storeMap.size());
274 | //把needSync置为false,如果在此之后有数据写入,则需要重新同步
275 | needSync.compareAndSet(true, false);
276 | observer.stopWatching();
277 | ReadWriteManager manager = new ReadWriteManager(sContext, name);
278 | manager.write(storeMap);
279 | //解除同步过程
280 | syncing.compareAndSet(true, false);
281 | Log.d(TAG, "write to file complete");
282 | //如果数据被更改,则需要重新同步
283 | if (needSync.get()) {
284 | Log.d(TAG, "need to sync again");
285 | postSyncTask();
286 | } else {
287 | Log.d(TAG, "do not need to sync, start watching");
288 | observer.startWatching();
289 | }
290 | }
291 | }
292 | }
293 |
294 | private class ReloadTask implements Runnable {
295 | @Override
296 | public void run() {
297 | reload();
298 | }
299 | }
300 |
301 | private class DataChangeObserver extends FileObserver {
302 |
303 | private static final int FILE_EVENTS = MODIFY | CLOSE_WRITE | DELETE;
304 |
305 | public DataChangeObserver(String path) {
306 | super(path, FILE_EVENTS);
307 | }
308 |
309 | @Override
310 | public void onEvent(int event, @Nullable String path) {
311 | Log.d(TAG, "DataChangeObserver: " + event);
312 | switch (event) {
313 | case CLOSE_WRITE:
314 | onCloseWrite(path);
315 | break;
316 | case DELETE:
317 | onDelete(path);
318 | break;
319 | }
320 | }
321 |
322 | public void onCloseWrite(String path) {
323 | if (syncing.get()) {
324 | //如果正在同步,则取消reload
325 | return;
326 | }
327 | SYNC_EXECUTOR.execute(new ReloadTask());
328 | }
329 |
330 | public void onDelete(String path) {
331 | keyValueMap.clear();
332 | }
333 | }
334 |
335 | private static class FspCache extends LruCache {
336 |
337 | private static final int DEFAULT_MAX_SIZE = (int) (Runtime.getRuntime().maxMemory() / 1024 / 16);
338 |
339 | public FspCache() {
340 | this(DEFAULT_MAX_SIZE);
341 | }
342 |
343 | public FspCache(int maxSize) {
344 | super(maxSize);
345 | }
346 |
347 | @Override
348 | protected int sizeOf(String key, FastSharedPreferences value) {
349 | int size = 0;
350 | if (value != null) {
351 | size = value.sizeOf();
352 | }
353 | Log.d(TAG, "FspCache sizeOf " + key + " is: " + size);
354 | return size;
355 | }
356 |
357 | @Override
358 | protected FastSharedPreferences create(String key) {
359 | return new FastSharedPreferences(key);
360 | }
361 |
362 | @Override
363 | protected void entryRemoved(boolean evicted, String key, FastSharedPreferences oldValue, FastSharedPreferences newValue) {
364 | Log.d(TAG, "FspCache entryRemoved: " + key);
365 | }
366 | }
367 | }
368 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/java/com/jeremy/fastsharedpreferences/io/IoUtil.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences.io;
2 |
3 | import java.io.Closeable;
4 | import java.io.File;
5 | import java.io.IOException;
6 |
7 |
8 | public final class IoUtil {
9 |
10 | private IoUtil() {
11 | }
12 |
13 | public static void closeSilently(Closeable closeable) {
14 | if (closeable != null) {
15 | try {
16 | closeable.close();
17 | } catch (IOException var2) {
18 | }
19 | }
20 | }
21 |
22 | public static boolean isFileExist(String path) {
23 | File file = new File(path);
24 | return file.exists();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/java/com/jeremy/fastsharedpreferences/io/ReadWriteManager.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences.io;
2 |
3 | import android.content.Context;
4 | import android.util.Log;
5 |
6 | import java.io.BufferedInputStream;
7 | import java.io.BufferedOutputStream;
8 | import java.io.File;
9 | import java.io.FileInputStream;
10 | import java.io.FileNotFoundException;
11 | import java.io.FileOutputStream;
12 | import java.io.IOException;
13 | import java.io.ObjectInputStream;
14 | import java.io.ObjectOutputStream;
15 | import java.io.RandomAccessFile;
16 | import java.nio.channels.FileChannel;
17 | import java.nio.channels.FileLock;
18 | import java.util.HashMap;
19 | import java.util.Map;
20 | import java.util.concurrent.locks.ReentrantLock;
21 |
22 | /**
23 | * Created by hailiangliao on 2018/3/16.
24 | */
25 |
26 | public class ReadWriteManager {
27 |
28 | private static final String TAG = "ReadWriteManager";
29 | private static final String DEFAULT_DIR_PATH = "fast_sp";
30 |
31 | public static String getFilePath(Context context, String name) {
32 | return context.getFilesDir().getAbsolutePath()
33 | + File.separator
34 | + DEFAULT_DIR_PATH
35 | + File.separator
36 | + name;
37 | }
38 |
39 | private String filePath;
40 | private String lockFilePath;
41 |
42 | public ReadWriteManager(Context context, String name) {
43 | this.filePath = getFilePath(context, name);
44 | this.lockFilePath = getFilePath(context, name + ".lock");
45 | // Log.d("ReadWriteManager", "filePath: " + filePath);
46 | prepare();
47 | }
48 |
49 | public void write(Object obj) {
50 | ObjectOutputStream oos = null;
51 | FileOutputStream fos = null;
52 | Lock lock = null;
53 | try {
54 | prepare();
55 | lock = new Lock(lockFilePath).lock();
56 | Log.d(TAG, "start write file: " + filePath);
57 | fos = new FileOutputStream(filePath);
58 | oos = new ObjectOutputStream(new BufferedOutputStream(fos));
59 | oos.writeObject(obj);
60 | oos.flush();
61 | } catch (Exception e) {
62 | e.printStackTrace();
63 | } finally {
64 | Log.d(TAG, "finish write file: " + filePath);
65 | IoUtil.closeSilently(oos);
66 | IoUtil.closeSilently(fos);
67 | if (lock != null) {
68 | lock.release();
69 | }
70 | }
71 | }
72 |
73 | public Object read() {
74 | if (!IoUtil.isFileExist(filePath)) {
75 | return null;
76 | }
77 | ObjectInputStream ois = null;
78 | FileInputStream fis = null;
79 | Lock lock = null;
80 | try {
81 | lock = new Lock(lockFilePath).lock();
82 | fis = new FileInputStream(filePath);
83 | ois = new ObjectInputStream(new BufferedInputStream(fis));
84 | return ois.readObject();
85 | } catch (Exception e) {
86 | e.printStackTrace();
87 | return null;
88 | } finally {
89 | IoUtil.closeSilently(ois);
90 | IoUtil.closeSilently(fis);
91 | if (lock != null) {
92 | lock.release();
93 | }
94 | }
95 | }
96 |
97 | private void prepare() {
98 | File file = new File(filePath);
99 | File parent = file.getParentFile();
100 | if (!parent.exists()) {
101 | parent.mkdirs();
102 | }
103 | }
104 |
105 | private static class Lock {
106 |
107 | private static final Map THREAD_LOCK_MAP = new HashMap<>();
108 |
109 | private static ReentrantLock getLock(String key) {
110 | synchronized (THREAD_LOCK_MAP) {
111 | if (!THREAD_LOCK_MAP.containsKey(key)) {
112 | THREAD_LOCK_MAP.put(key, new ReentrantLock());
113 | }
114 | return THREAD_LOCK_MAP.get(key);
115 | }
116 | }
117 |
118 | private final String lockFilePath;
119 | private FileOutputStream fos;
120 | private FileChannel channel;
121 | private FileLock fileLock;
122 | private ReentrantLock threadLock;
123 |
124 | public Lock(String lockFilePath) {
125 | this.lockFilePath = lockFilePath;
126 | this.threadLock = getLock(lockFilePath);
127 | File file = new File(this.lockFilePath);
128 | if (!file.exists()) {
129 | try {
130 | file.createNewFile();
131 | } catch (IOException e) {
132 | e.printStackTrace();
133 | }
134 | }
135 | }
136 |
137 | public Lock lock() throws IOException {
138 | threadLock.lock();
139 | fos = new FileOutputStream(lockFilePath);
140 | channel = fos.getChannel();
141 | fileLock = channel.lock();
142 | return this;
143 | }
144 |
145 | public void release() {
146 | if (fileLock != null) {
147 | try {
148 | fileLock.release();
149 | } catch (IOException e) {
150 | e.printStackTrace();
151 | }
152 | }
153 | IoUtil.closeSilently(channel);
154 | IoUtil.closeSilently(fos);
155 | threadLock.unlock();
156 | }
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | fastsharedpreferences
3 |
4 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/test/java/com/jeremy/fastsharedpreferences/FastSharedPreferencesTest.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences;
2 |
3 | import android.content.Context;
4 |
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.mockito.Mock;
8 | import org.mockito.MockitoAnnotations;
9 |
10 | import java.io.File;
11 |
12 | import static org.mockito.Mockito.*;
13 | import static org.junit.Assert.*;
14 |
15 | /**
16 | * Created by liaohailiang on 2018/10/25.
17 | */
18 | public class FastSharedPreferencesTest {
19 |
20 | @Mock
21 | Context context;
22 |
23 | @Mock
24 | Context appContext;
25 |
26 | @Before
27 | public void setUp() {
28 | MockitoAnnotations.initMocks(this);
29 | when(context.getApplicationContext()).thenReturn(appContext);
30 | File file = new File("./build/");
31 | when(appContext.getFilesDir()).thenReturn(file);
32 | FastSharedPreferences.init(context);
33 | }
34 |
35 | @Test
36 | public void testContext() {
37 | assertNotNull(context);
38 | }
39 |
40 | @Test
41 | public void testLoad() {
42 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_load");
43 | assertNotNull(sharedPreferences);
44 | }
45 |
46 | @Test
47 | public void testWriteString() {
48 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_string");
49 | sharedPreferences.edit().putString("test_key", "test_value").apply();
50 | sleep(100);
51 | sharedPreferences = FastSharedPreferences.get("test_write_string");
52 | assertEquals(sharedPreferences.getString("test_key", ""), "test_value");
53 | }
54 |
55 | @Test
56 | public void testWriteInteger() {
57 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_integer");
58 | sharedPreferences.edit().putInt("test_key", 100).apply();
59 | sleep(100);
60 | sharedPreferences = FastSharedPreferences.get("test_write_integer");
61 | assertEquals(sharedPreferences.getInt("test_key", -1), 100);
62 | }
63 |
64 | @Test
65 | public void testWriteLong() {
66 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_long");
67 | sharedPreferences.edit().putLong("test_key", 100).apply();
68 | sleep(100);
69 | sharedPreferences = FastSharedPreferences.get("test_write_long");
70 | assertEquals(sharedPreferences.getLong("test_key", -1), 100);
71 | }
72 |
73 | @Test
74 | public void testWriteFloat() {
75 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_float");
76 | sharedPreferences.edit().putFloat("test_key", 100.0f).apply();
77 | sleep(100);
78 | sharedPreferences = FastSharedPreferences.get("test_write_float");
79 | assertTrue(sharedPreferences.getFloat("test_key", -1) == 100.0f);
80 | }
81 |
82 | @Test
83 | public void testWriteBoolean() {
84 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_bool");
85 | sharedPreferences.edit().putBoolean("test_key", true).apply();
86 | sleep(100);
87 | sharedPreferences = FastSharedPreferences.get("test_write_bool");
88 | assertEquals(sharedPreferences.getBoolean("test_key", false), true);
89 | }
90 |
91 | @Test
92 | public void testWriteSerializable() {
93 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_ser");
94 | sharedPreferences.edit().putSerializable("test_key",
95 | new TestBean("test_str", 100)).apply();
96 | sleep(100);
97 | sharedPreferences = FastSharedPreferences.get("test_write_ser");
98 | TestBean testBean = (TestBean) sharedPreferences.getSerializable("test_key", null);
99 | assertNotNull(testBean);
100 | assertEquals(testBean.getStrValue(), "test_str");
101 | assertEquals(testBean.getIntValue(), 100);
102 | }
103 |
104 | @Test
105 | public void testWriteIntegers() {
106 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_int");
107 | for (int i = 0; i < 1000; i++) {
108 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
109 | }
110 | sleep(200);
111 | sharedPreferences = FastSharedPreferences.get("test_write_int");
112 | for (int i = 0; i < 1000; i++) {
113 | assertEquals(sharedPreferences.getInt("test_key_" + i, -1), i);
114 | }
115 | }
116 |
117 | @Test
118 | public void testWriteCount() {
119 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_count");
120 | sharedPreferences.edit().clear().commit();
121 | sleep(200);
122 | for (int i = 0; i < 10000; i++) {
123 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
124 | }
125 | sleep(1000);
126 | sharedPreferences = FastSharedPreferences.get("test_write_count");
127 | assertEquals(sharedPreferences.getAll().size(), 10000);
128 | }
129 |
130 | @Test
131 | public void testRemove() {
132 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_re");
133 | sharedPreferences.edit().putString("test_key", "test_value").apply();
134 | sleep(100);
135 | sharedPreferences.edit().remove("test_key").apply();
136 | sleep(100);
137 | sharedPreferences = FastSharedPreferences.get("test_write_re");
138 | assertEquals(sharedPreferences.contains("test_key"), false);
139 | }
140 |
141 | @Test
142 | public void testClear() {
143 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get("test_write_cl");
144 | for (int i = 0; i < 1000; i++) {
145 | sharedPreferences.edit().putInt("test_key_" + i, i).apply();
146 | }
147 | sleep(200);
148 | sharedPreferences.edit().clear().apply();
149 | sleep(100);
150 | sharedPreferences = FastSharedPreferences.get("test_write_cl");
151 | assertEquals(sharedPreferences.getAll().size(), 0);
152 | }
153 |
154 | private void sleep(long time) {
155 | try {
156 | Thread.sleep(time);
157 | } catch (Exception e) {
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/FastSharedPreferences/fastsharedpreferences/src/test/java/com/jeremy/fastsharedpreferences/TestBean.java:
--------------------------------------------------------------------------------
1 | package com.jeremy.fastsharedpreferences;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * Created by liaohailiang on 2018/10/25.
7 | */
8 | public class TestBean implements Serializable {
9 |
10 | private String strValue;
11 | private int intValue;
12 |
13 | public TestBean() {
14 | }
15 |
16 | public TestBean(String strValue, int intValue) {
17 | this.strValue = strValue;
18 | this.intValue = intValue;
19 | }
20 |
21 | public String getStrValue() {
22 | return strValue;
23 | }
24 |
25 | public void setStrValue(String strValue) {
26 | this.strValue = strValue;
27 | }
28 |
29 | public int getIntValue() {
30 | return intValue;
31 | }
32 |
33 | public void setIntValue(int intValue) {
34 | this.intValue = intValue;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/FastSharedPreferences/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
15 |
16 |
--------------------------------------------------------------------------------
/FastSharedPreferences/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JeremyLiao/FastSharedPreferences/5fdeb58a913d114f1d97d55aeaa4e8a15abfa199/FastSharedPreferences/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/FastSharedPreferences/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
6 |
--------------------------------------------------------------------------------
/FastSharedPreferences/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/FastSharedPreferences/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/FastSharedPreferences/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':fastsharedpreferences'
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # FastSharedPreferences——高性能Android key-value组件
2 | FastSharedPreferences是一个Android平台的高性能key-value组件。
3 | ## FastSharedPreferences特点
4 | 1. 实现了SharedPreferences和SharedPreferences.Editor接口,便于无缝替换SharedPreferences。
5 | 2. 增强了SharedPreferences,增加了写入/读取Serializable的接口。
6 | 3. 高效的写入/读取性能,读写性能相比SharedPreferences增强了200-300倍
7 | 4. 纯java实现,很好的兼容性和稳定性
8 | 5. 实现代码简洁,aar体积很小
9 | 6. 支持跨进程使用(同时实现高性能和跨进程的难度超出预期,这一点后面会逐渐优化)
10 | 7. 支持基于LRU的缓存管理,减少内存使用
11 |
12 | ## FastSharedPreferences原理
13 | - **适合高强度/高频次写入读取**
14 |
15 | FastSharedPreferences由Cache层和同步层构成,特别适合高强度/高频次写入读取数据。
16 | - **内存Cache**
17 |
18 | 基于ConcurrentHashMap的内存Cache层,不仅提高了写入性能,也极大的提高了读取性能。
19 | - **同步管理**
20 |
21 | 通过脏数据标记等技术,减少了同步的次数,使得慢速的I/O不再成为读写速度的瓶颈。
22 |
23 | 
24 | ## FastSharedPreferences使用指南
25 | ### 接入
26 |
27 | ```
28 | dependencies {
29 | compile 'com.jeremyliao:fast-sharedpreferences:0.0.1'
30 | }
31 | ```
32 |
33 | ### 快速上手
34 | ##### 在application onCreate中初始化:
35 |
36 | ```
37 | FastSharedPreferences.init(context);
38 | ```
39 |
40 | ##### 用法和SharedPreferences几乎完全一致,例如:
41 | - [x] 写入一个整数
42 |
43 | ```
44 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(FSP_ID);
45 | sharedPreferences.edit().putInt("test_key", 100).apply();
46 | ```
47 | - [x] 读取一个整数
48 |
49 | ```
50 | FastSharedPreferences sharedPreferences = FastSharedPreferences.get(FSP_ID);
51 | int ret = sharedPreferences.getInt("test_key", -1);
52 | ```
53 |
54 | ## 性能对比
55 | 我们将 FastSharedPreferences同 SharedPreferences、SQLite以及腾讯的MMKV进行对比,测试的结果是对每项测试重复200次取平均值(对SharedPreferences和SQLite没有重复这么多次,因为时间太长了:))。相关测试代码参见[benchmark](https://github.com/JeremyLiao/FastSharedPreferences/tree/master/FastSharedPreferences/app/src/main/java/com/jeremy/fspdemo/benchmark)。
56 |
57 | - 写入1000个整数
58 |
59 | 
60 |
61 | (测试机器是 Nexus 6 64G,Android 7.1.1,每组操作重复 200次,时间单位是 ms)
62 |
63 | - 读取1000个整数
64 |
65 | 
66 |
67 | (测试机器是 Nexus 6 64G,Android 7.1.1,每组操作重复 200次,时间单位是 ms)
68 |
--------------------------------------------------------------------------------