Cache results



  • I have an expensive function that returns a variable result.
    I only want to call this function once per tick but want to access and change the result multiple times per tick.
    What are some recommendations on how to achieve this?



  • Simply store the result in the global name space.

    global.yourResult = yourFunc();
    


  • Is it a good practice to do so?



  • Generally spoken - depends. Screeps wise spoken - yes.

    You should of course apply a proper namespacing paradigm to prevent collisions. E.g., you could create a global namespace Cache, where you store all you cached results. The simplest approach would be:

    
    global.Cache = {};
    Cache.rooms = {};
    Cache.rooms[room] = {};
    Cache.rooms[room].workersThatNeedEnergy = room.findWorkersThatNeedEnergy();
    Cache.rooms[room].emptyExtensions = room.findEmptyExtensions();
    
    
    

    If you go fancy, you create a unified cache wrapper which uses the global space for tick based cache and for more persistent results the Memory. Then you call it to cache the result directly inside the according functions to transparently hand out the real search for the first time and for consecutive calls the cached result set.



  • so something like...

    Function = function (room) {
        if (global.Cache.rooms[room].FunctionName === undefined) {
            if (global.Cache.rooms[room] === undefined) {
                if (global.Cache.rooms === undefined) {
                    if (global.Cache === undefined) {
                        global.Cache = {};
                    }
                    global.Cache.rooms = {};
                }
                global.Cache.rooms[room] = {};
            }
            global.Cache.rooms[room].FunctionName = FunctionCode;
        }
        return global.Cache.rooms[room].FunctionName;
    }
    
    ?
    is there a way I could format that better? more readable etc.?
    


  • Like this?
    javascript
    Function = function (room)
    {
    global.Cache = global.Cache || {};
    global.Cache.rooms = global.Cache.rooms || {};
    global.Cache.rooms [room] = global.Cache.rooms [room] || {};
    global.Cache.rooms [room].FunctionName = global.Cache.rooms [room].FunctionName || FunctionCode;
    return global.Cache.rooms[room].FunctionName;
    }



  • Ohh... markdown
    javascript
    var Foo = function (room)
    {
    global.Cache = global.Cache || {};
    global.Cache.rooms = global.Cache.rooms || {};
    global.Cache.rooms [room] = global.Cache.rooms [room] || {};
    global.Cache.rooms [room].FunctionName = global.Cache.rooms [room].FunctionName || FunctionCode;
    return global.Cache.rooms[room].FunctionName;
    }