perf: resource cache

This commit is contained in:
cha0s 2024-07-10 14:14:10 -05:00
parent c344b65534
commit 348a24d8a2
2 changed files with 48 additions and 5 deletions

View File

@ -25,8 +25,21 @@ export default class ClientEcs extends Ecs {
return cache.get(uri);
}
async readJson(uri) {
const chars = await this.readAsset(uri);
return chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {};
const key = ['$$json', uri].join(':');
if (!cache.has(key)) {
let promise, resolve, reject;
promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
cache.set(key, promise);
this.readAsset(uri)
.then((chars) => {
resolve(chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {});
})
.catch(reject);
}
return cache.get(key);
}
async readScript(uri, context = {}) {
const code = await this.readAsset(uri);

View File

@ -11,6 +11,12 @@ import createHomestead from './create-homestead.js';
import createHouse from './create-house.js';
import createPlayer from './create-player.js';
import {LRUCache} from 'lru-cache';
const cache = new LRUCache({
max: 128,
});
export default class Engine {
connectedPlayers = new Map();
@ -38,11 +44,35 @@ export default class Engine {
return engine.frame;
}
async readAsset(uri) {
return server.readAsset(uri);
if (!cache.has(uri)) {
let promise, resolve, reject;
promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
cache.set(uri, promise);
server.readAsset(uri)
.then(resolve)
.catch(reject);
}
return cache.get(uri);
}
async readJson(uri) {
const chars = await this.readAsset(uri);
return chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {};
const key = ['$$json', uri].join(':');
if (!cache.has(key)) {
let promise, resolve, reject;
promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
cache.set(key, promise);
this.readAsset(uri)
.then((chars) => {
resolve(chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {});
})
.catch(reject);
}
return cache.get(key);
}
async readScript(uri, context) {
if (!uri) {