Huge (and unstable) Cpu cost of createFlag() function



  • I'm working on an automated construction planning script, but I'm constantly getting the error that I'm using too much cpu.

    After some testing with the following code on the main server:

    var start = Game.cpu.getUsed();
    for( var i = 0; i < 5; i++) {
         Game.rooms['E13N21'].createFlag(10 + i,10 + i,null);
    }
    console.log("Cpu used " + (Game.cpu.getUsed() - start));

     I'm getting the following results:

    [11:17:12 PM]Cpu used 139.773812

    [11:17:16 PM]Cpu used 414.195368

    [11:17:19 PM]Cpu used 180.817071

    [11:17:21 PM]Cpu used 193.585359

    [11:17:24 PM]Cpu used 165.31457400000002

    [11:17:27 PM]Cpu used 200.04942400000002

    [11:17:31 PM]Cpu used 193.477699

    [11:17:34 PM]Cpu used 417.859175

    [11:17:37 PM]Cpu used 196.759669

    [11:17:40 PM]Cpu used 195.42644199999998

    [11:17:42 PM]Cpu used 206.136035

    [11:17:46 PM]Cpu used 182.28700999999998

    [11:17:49 PM]Cpu used 229.220531

    [11:17:52 PM]Cpu used 426.39616700000005

    [11:17:56 PM]Cpu used 212.994109

    [11:17:59 PM]Cpu used 205.381853

    [11:18:02 PM]Cpu used 234.454314

    [11:18:05 PM]Cpu used 278.907558

    [11:18:08 PM]Cpu used 254.071182

    [11:18:12 PM]Cpu used 297.75649300000003

    [11:18:14 PM]Cpu used 303.071679

    [11:18:16 PM]Cpu used 292.183037
     
    I'm not 100% sure if createFlag was meant to use 40-50 cpu, but it also doesn't follow the description from the docs that it's a constant cost.


  • This issue is due to the way unnamed flags are created.  The names are checked against the list of existing flags by iterating over the existing flag memory objects using "Flag" + X, but the result is not cached in memory for subsequent calls within the same tick, resulting in the iteration being done for every flag creation request.  Aside from caching the value, the iteration could be changed into some sort of binary divide-and-conquer of flag namespaces (i.e. checking if Flag1 exists, checking if Flag10 exists, if both do jump to Flag50, then just slice by portions until you narrow down the beginning of the open contiguous area).

     

    The cpu cost is drastically reduced when creating named flags.



  • Maybe you should do your own flag name pool system?