android - Why apply() is no faster than commit() in SharedPreferences.Editor -


i learned difference between apply() , commit() of sharedpreferences.editor. apply() said asynchronous , safe run on ui thread; commit() said synchronous , not suitable run on ui thread. did simple test click listener in mainactivity:

sharedpreferences sharedpreferences = mainactivity.this.getsharedpreferences("synced", 0); sharedpreferences.editor editor = sharedpreferences.edit(); (int = 0; < 100000; ++i) {     editor.putstring("index" + i, "index" + i); } log.e("test", system.nanotime() + " sync "); editor.commit(); log.e("test", system.nanotime() + " sync " + sharedpreferences.getstring("index99999", "null"));  sharedpreferences sharedpreferences2 = mainactivity.this.getsharedpreferences("asynced", 0); sharedpreferences.editor editor2 = sharedpreferences2.edit(); (int = 0; < 100000; ++i) {     editor2.putstring("index2" + i, "index2" + i); } log.e("test", system.nanotime() + " async "); editor2.apply(); log.e("test", system.nanotime() + " async " + sharedpreferences2.getstring("index299999", "null")); 

i run several time , received same result this:

05-25 01:11:44.608 16109-16109/darklord.preferencestest e/test: 1295614410392 sync  05-25 01:11:44.667 16109-16109/darklord.preferencestest e/test: 1295669350041 sync index99999 05-25 01:11:45.257 16109-16109/darklord.preferencestest e/test: 1296262306521 async  05-25 01:11:45.317 16109-16109/darklord.preferencestest e/test: 1296317374397 async null 

i expecting apply() must faster commit(), result turned out same. both not suitable run on ui thread. why happens?

edit: log should be

05-25 01:11:44.608 16109-16109/darklord.preferencestest e/test: 1295614410392 sync  05-25 01:11:44.667 16109-16109/darklord.preferencestest e/test: 1295669350041 sync index99999 05-25 01:11:45.257 16109-16109/darklord.preferencestest e/test: 1296262306521 async  05-25 01:11:45.317 16109-16109/darklord.preferencestest e/test: 1296317374397 async index249999 

i testing on emulator api 17.

the problem you're reading values in-memory

sharedpreference created before.

according documentation,

apply() commits changes in-memory sharedpreferences starts asynchronous commit disk

therefore, in-memory sharedpreference updated immediately.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -