问题描述
我读了一些关于Firebase缓存数据的说法。
所以我跑了读取了大量的数据(大约400KB)。
以下是相关的代码。
firebase.initializeApp(config);
var counter = 0;
console.time('firebase回答');
firebase.database()。ref('texts')。once('value',onData);
函数onData(快照){
console.timeEnd('firebase回答');
counter ++;
if(counter> 20)return;
$ b $ setTimeout(function(){
console.time('firebase回答');
firebase.database()。ref('texts')。once('value ',onData);
},2000);
$ b正如你所看到的,它第一次加载数据需要一段时间,接下来的调用花费的时间要少得多。
I read somewhere a claim that Firebase caches the data.
So I ran this test that reads a semi large volume of data (about 400KB).
Here is the relevant code.
firebase.initializeApp(config); var counter = 0; console.time('firebase answered in'); firebase.database().ref('texts').once('value',onData); function onData(snapshot){ console.timeEnd('firebase answered in'); counter ++; if(counter > 20) return; setTimeout(function(){ console.time('firebase answered in'); firebase.database().ref('texts').once('value',onData); },2000); }As you can see, the first time it loads data it takes a while, and subsequent calls take much less time.
But, still, if the data is cached locally ~200ms (sometimes more) seems like a lot of time to access local data. Enough for the user to perceive a delay when rendering the UI.
So is Firebase caching the data? What is happening in those ~200ms?
解决方案Firebase caches the data (in memory) for as long as there is an active listener for that data.
Since your code uses only once() listener, the listener is detached immediately when the data is received (before your callback is invoked) and the data is cleared from the cache. That means that is has to get the data from the servers for each once(), which apparently is a 200ms round-trip in your case. The first load is slower, because the connection is likely established in that call.
A quick trick to verify this is to add a permanent listener before starting your loop:
firebase.initializeApp(config); var counter = 0; console.time('firebase answered in'); firebase.database().ref('texts').on('value',function() {}); firebase.database().ref('texts').once('value',onData); function onData(snapshot){ console.timeEnd('firebase answered in'); counter ++; if(counter > 20) return; setTimeout(function(){ console.time('firebase answered in'); firebase.database().ref('texts').once('value',onData); },2000); }With that simple change, the logging turns into:
这篇关于Firebase是否缓存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!