User:Braindawg/performance: Difference between revisions
|  (→Arrays) |  (update to use new benchmarking tool) | ||
| Line 1: | Line 1: | ||
| This page includes tips and tricks for optimizing [[VScript]] performance.  All of these performance tests were done in {{tf2}} and many can be used in other {{src13}}-based titles.  Your mileage may vary in VScript supported games prior to the SDK update ({{l4d2}}{{portal2}}{{asw}}). | This page includes tips and tricks for optimizing [[VScript]] performance.  All of these performance tests were done in {{tf2}} and many can be used in other {{src13}}-based titles.  Your mileage may vary in VScript supported games prior to the SDK update ({{l4d2}}{{portal2}}{{asw}}).  Benchmarks figure come from [https://github.com/potato-tf/vscript-benchmark this benchmarking tool]. | ||
| {{Warning|Only optimize your scripts if you need to!  Some of these tips may introduce extra unnecessary complexity to your projects.  Premature optimization without knowing where your performance issues actually come from is extremely ill-advised.}} | {{Warning|Only optimize your scripts if you need to!  Some of these tips may introduce extra unnecessary complexity to your projects.  Premature optimization without knowing where your performance issues actually come from is extremely ill-advised.}} | ||
| {{Note| | {{Note|The built-in performance counter for VScript has a lot of "noise", and depends heavily on other things executing on the main game server thread.  Memory speed, CPU speed, And even file I/O, will greatly impact your results and the variance between them, even on repeated runs of the same code.  The numbers shown here are averages/ballpark figures taken from 5 or more repeated runs.  A third-party benchmarking tool does exist, however there is unfortunately no convenient download link for it.  Look around mapping/content creation discord servers for it.}} | ||
| = Folding = | |||
| == Functions ==  | |||
| Folding functions in the context of VScript means folding them into the root table.  This only needs to be done once on script load, and is recommended for functions that are commonly used. | Folding functions in the context of VScript means folding them into the root table.  This only needs to be done once on script load, and is recommended for functions that are commonly used. | ||
| === Benchmark === | === Benchmark === | ||
| {{Note|Benchmark done on  | {{Note|Benchmark done on mvm_bigrock}} | ||
| <source lang=js> | <source lang=js> | ||
| : | /*********************************************************************************************************** | ||
| local  |  * FOLDING:                                                                                                * | ||
|  * Folding functions from their original scope into local/root scope is noticeably faster (~15-30%)        * | |||
|  * skips extra lookup instructions, also less verbose                                                      * | |||
|  ***********************************************************************************************************/ | |||
| local GetPropString = NetProps.GetPropString.bindenv( NetProps ) | |||
| local GetPropBool = NetProps.GetPropBool.bindenv( NetProps ) | |||
| const MAX_EDICTS = 2048 | |||
| function Benchmark::Unfolded() { | |||
|     for ( local i = 0, ent; i < Constants.Server.MAX_EDICTS; ent = EntIndexToHScript( i ), i++ ) { | |||
|         if ( ent ) { | |||
|             NetProps.GetPropString( ent, "m_iName" ) | |||
|             NetProps.GetPropString( ent, "m_iClassname" ) | |||
|             NetProps.GetPropBool( ent, "m_bForcePurgeFixedupStrings" ) | |||
|         } | |||
|     } | |||
| } | } | ||
| //  | // 20% faster, maybe more | ||
| function Benchmark::Folded() { | |||
|     for ( local i = 0, ent; i < MAX_EDICTS; ent = EntIndexToHScript( i ), i++ ) { | |||
|         if ( ent ) { | |||
|             GetPropString( ent, "m_iName" ) | |||
|             GetPropString( ent, "m_iClassname" ) | |||
|             GetPropBool( ent, "m_bForcePurgeFixedupStrings" ) | |||
|         } | |||
|     } | |||
| } | |||
| </source> | </source> | ||
| Line 41: | Line 58: | ||
| |- | |- | ||
| |<code>Unfolded</code> | |<code>Unfolded</code> | ||
| |<code> | |<code>1.76ms</code> | ||
| |- | |- | ||
| |<code>Folded</code> | |<code>Folded</code> | ||
| |<code> | |<code>1.32ms</code> | ||
| |- | |- | ||
| |} | |} | ||
| == Constants == | == Constants == | ||
| Similar to folding functions, folding pre-defined Constant values into the constant table (or the root table) increases performance significantly. | Similar to folding functions, folding pre-defined Constant values into the constant table (or the root table) increases performance significantly. | ||
| ===Benchmark=== | === Benchmark === | ||
| <source lang=js> | <source lang=js> | ||
| local  | local _CONST = getconsttable() | ||
| // fold every pre-defined constant into the const table | |||
| if ( !( "ConstantNamingConvention" in ROOT ) ) | |||
| 	foreach( a, b in Constants ) | |||
| 		foreach( k, v in b ) | |||
|             _CONST[k] <- v != null ? v : 0 | |||
| setconsttable(_CONST) | |||
| local  | |||
| function Benchmark::UnfoldedConst() { | |||
|     for (local i = 1; i <= Constants.Server.MAX_EDICTS; i++) | |||
|         local temp = i | |||
| } | |||
| function Benchmark::FoldedConst() { | |||
| for (local i = 1; i <= MAX_EDICTS; i++) |     for (local i = 1; i <= MAX_EDICTS; i++) | ||
|         local temp = i | |||
| } | |||
| </source> | </source> | ||
| Line 76: | Line 102: | ||
| |- | |- | ||
| |<code>Unfolded</code> | |<code>Unfolded</code> | ||
| |<code>0. | |<code>0.356ms</code> | ||
| |- | |- | ||
| |<code> | |<code>Folded</code> | ||
| |<code>0. | |<code>0.033ms</code> | ||
| |- | |- | ||
| |} | |} | ||
| == Root table vs Constant table == | |||
| Unlike values inserted into the root table, values inserted into the constant table are cached at the pre-processor level.  What this means is, while accessing them is faster, it may not be feasible to fold your constants into the constant table if they are folded in the same script file that references them. | Unlike values inserted into the root table, values inserted into the constant table are cached at the pre-processor level.  What this means is, while accessing them is faster, it may not be feasible to fold your constants into the constant table if they are folded in the same script file that references them. | ||
| If you intend to insert values into the constant table, you must do this ''before'' any other scripts are executed, otherwise your script will not be able to read any values from it. | If you intend to insert values into the constant table (<code>const</code> keyword or <code>getconsttable().foo <- "bar"</code>), you must do this ''before'' any other scripts are executed, otherwise your script will not be able to read any values from it. | ||
| == Benchmark == | |||
| <source lang=js> | <source lang=js> | ||
| :: | ::SomeGlobalVar <- 0 | ||
| const  | const GLOBAL_VAR = 0x7FFFFFFF | ||
| function Benchmark::RootSetLookup() { | |||
| for (local i =  |     for (local i = 1; i <= 10000; i++) | ||
|         local temp = ::SomeGlobalVar | |||
| } | |||
| // ~20-40% faster | |||
| function Benchmark::ConstSetLookup() { | |||
|     for (local i = 1; i <= 10000; i++) | |||
|         local temp = GLOBAL_VAR | |||
| } | |||
| </source> | </source> | ||
| Line 107: | Line 139: | ||
| ! Results | ! Results | ||
| |- | |- | ||
| |<code> | |<code>Root</code> | ||
| |<code>0. | |<code>0.267ms</code> | ||
| |- | |- | ||
| |<code> | |<code>Const</code> | ||
| |<code>0. | |<code>0.154ms</code> | ||
| |- | |- | ||
| |} | |} | ||
| = String Formatting = | |||
| Squirrel supports two main ways to format strings: Concatenation using the + symbol, and the <code>format()</code> function.  <code>format()</code> is significantly faster than concatenation. | Squirrel supports two main ways to format strings: Concatenation using the + symbol, and the <code>format()</code> function.  <code>format()</code> is significantly faster than concatenation. | ||
| Line 121: | Line 153: | ||
| {{Tip|For formatting entity handles and functions, use <code>.tostring()</code> and format it as a string}} | {{Tip|For formatting entity handles and functions, use <code>.tostring()</code> and format it as a string}} | ||
| == ToKVString == | |||
| the <code>TOKVString()</code> VScript function takes a Vector/QAngle and formats the values into a string.  For example, <code>Vector(0, 0, 0).ToKVString()</code> would be <code>"0 0 0"</code> | the <code>TOKVString()</code> VScript function takes a Vector/QAngle and formats the values into a string.  For example, <code>Vector(0, 0, 0).ToKVString()</code> would be <code>"0 0 0"</code> | ||
| Line 127: | Line 159: | ||
| On top of being less cumbersome to write, <code>ToKVString()</code> is marginally faster than <code>format()</code>. | On top of being less cumbersome to write, <code>ToKVString()</code> is marginally faster than <code>format()</code>. | ||
| However, when formatting multiple <code>ToKVString()</code> outputs into a new string, concatenation is faster due to less function calls. | |||
| == Benchmark ==   | |||
| <source lang=js> | <source lang=js> | ||
| function Benchmark::StringConcat() { | |||
| local  | |||
|     for ( local i = 0; i < 10000; i++ ) | |||
|         kvstring = mins.x + "," + mins.y + "," + mins.z + "," + maxs.x + "," + maxs.y + "," + maxs.z | |||
| } | |||
| function Benchmark::StringFormat() { | |||
| for (local i = 0; i < 10000; i++) |     for ( local i = 0; i < 10000; i++ ) | ||
|         kvstring = format("%g,%g,%g,%g,%g,%g", mins.x, mins.y, mins.z, maxs.x, maxs.y, maxs.z) | |||
| } | |||
| function Benchmark::KVStringFormat() { | |||
|      for (local i = 0; i < 10000; i++ ) | |||
| for (local i = 0; i < 10000; i++) |         kvstring = format("%s %s", mins.ToKVString(), maxs.ToKVString()) | ||
| } | |||
| function Benchmark::KVStringConcat() { | |||
| for (local i = 0; i < 10000; i++) |     for (local i = 0; i < 10000; i++ ) | ||
|         kvstring = mins.ToKVString() + " " + maxs.ToKVString() | |||
| } | |||
| </source> | </source> | ||
| Line 156: | Line 195: | ||
| ! Results | ! Results | ||
| |- | |- | ||
| |<code> | |<code>StringConcat</code> | ||
| |<code> | |<code>35.0847ms</code> | ||
| |- | |- | ||
| |<code> | |<code>StringFormat</code> | ||
| |<code> | |<code>23.0143ms</code> | ||
| |- | |- | ||
| |<code> | |<code>KVStringFormat</code> | ||
| |<code> 19.9377ms</code> | |<code> 19.9377ms</code> | ||
| |- | |- | ||
| |<code> | |<code>KVStringConcat</code> | ||
| |<code>18. | |<code>18.3142ms</code> | ||
| |} | |} | ||
| = Spawning Entities = | |||
| in VScript, there are four common ways to spawn entities: | in VScript, there are four common ways to spawn entities: | ||
| Line 181: | Line 220: | ||
| - point_script_template entity + AddTemplate | - point_script_template entity + AddTemplate | ||
| == CreateByClassname + DispatchSpawn vs SpawnEntityFromTable == | |||
| In general, performance is not a major concern when spawning entities.  In special circumstances though, you may need to spawn and kill a temporary entity in an already expensive function.  A notable example of an entity that would need this is [[trigger_stun]].  This entity will not attempt to re-stun the same player multiple times, so it is not possible to spawn a single entity and repeatedly fire StartTouch/EndTouch on the same target. | In general, performance is not a major concern when spawning entities.  In special circumstances though, you may need to spawn and kill a temporary entity in an already expensive function.  A notable example of an entity that would need this is [[trigger_stun]].  This entity will not attempt to re-stun the same player multiple times, so it is not possible to spawn a single entity and repeatedly fire StartTouch/EndTouch on the same target. | ||
| Line 187: | Line 226: | ||
| In situations like this, CreateByClassname + DispatchSpawn is roughly 4x faster in comparison to <code>SpawnEntityFromTable</code>. | In situations like this, CreateByClassname + DispatchSpawn is roughly 4x faster in comparison to <code>SpawnEntityFromTable</code>. | ||
| == Benchmark == | |||
| <source lang=js> | <source lang=js> | ||
| local CreateByClassname = Entities.CreateByClassname.bindenv( Entities ) | |||
| local SetPropBool = NetProps.SetPropBool.bindenv( NetProps ) | |||
| local SetPropString = NetProps.SetPropString.bindenv( NetProps ) | |||
| local DispatchSpawn = Entities.DispatchSpawn.bindenv( Entities ) | |||
| // anywhere from 15-30% faster for single entity spawning | |||
| // The table passed to SpawnEntityFromTable needs to be interpreted and converted to something C++ can understand | |||
| // also, wide performance variations are likely due to garbage collection on the passed table | |||
| }) | // meanwhile CreateByClassname/netprop/keyvaluefromstring are simple 1:1 C++ bindings | ||
| function Benchmark::ByClassname() { | |||
|      for (local i = 0; i < 100; i++) { | |||
|         local ent = CreateByClassname( "logic_relay" ) | |||
|         DispatchSpawn( ent ) | |||
|         SetPropString( ent, "m_iName", "__relay" ) | |||
|      } | |||
| } | |||
| function Benchmark::FromTable() { | |||
|     for (local i = 0; i < 100; i++) { | |||
|         SpawnEntityFromTable( "logic_relay", { targetname = "__relay" } ) | |||
|     } | |||
| } | |||
| </source> | </source> | ||
| Line 223: | Line 270: | ||
| |} | |} | ||
| == SpawnEntityGroupFromTable vs point_script_template == | |||
| When spawning multiple entities at the same time, it is more efficient to use either <code>SpawnEntityGroupFromTable</code> or a [[point_script_template]] entity.  These options also have the added benefit of respecting parent hierarchy, so the <code>parentname</code> keyvalue works as intended. | When spawning multiple entities at the same time, it is more efficient to use either <code>SpawnEntityGroupFromTable</code> or a [[point_script_template]] entity.  These options also have the added benefit of respecting parent hierarchy, so the <code>parentname</code> keyvalue works as intended. | ||
| Line 229: | Line 276: | ||
| point_script_template is both more flexible and faster.  SpawnEntityGroupFromTable has several major limitations in comparison to point_script_template, and is generally not recommended.  See the [[Team_Fortress_2/Scripting/Script_Functions#CPointScriptTemplate|VScript documentation]] for more details on how to use point_script_template. | point_script_template is both more flexible and faster.  SpawnEntityGroupFromTable has several major limitations in comparison to point_script_template, and is generally not recommended.  See the [[Team_Fortress_2/Scripting/Script_Functions#CPointScriptTemplate|VScript documentation]] for more details on how to use point_script_template. | ||
| == Benchmark == | |||
| <source lang=js> | <source lang=js> | ||
| //spawn origins are right outside of bigrock spawn | function Benchmark::EntityGroupFromTable() { | ||
| SpawnEntityGroupFromTable({ | |||
|     // spawn origins are right outside of bigrock spawn | |||
|     SpawnEntityGroupFromTable({ | |||
|         [0] = { | |||
|             func_rotating = | |||
|             { | |||
|                 message = "hl1/ambience/labdrone2.wav", | |||
|                 volume = 8, | |||
|                 responsecontext = "-1 -1 -1 1 1 1", | |||
|                 targetname = "crystal_spin", | |||
|                 vscripts = "rotatefix", // see func_rotating vdc page for this | |||
|                 spawnflags = 65, | |||
|                 solidbsp = 0, | |||
|                 rendermode = 10, | |||
|                 rendercolor = "255 255 255", | |||
|                 renderamt = 255, | |||
|                 maxspeed = 48, | |||
|                 fanfriction = 20, | |||
|                 origin = Vector(278.900513, -2033.692993, 516.067200), | |||
|             } | |||
|         }, | |||
|         [2] = { | |||
|             tf_glow = | |||
|             { | |||
|                 targetname = "crystalglow", | |||
|                 parentname = "crystal", | |||
|                 target = "crystal", | |||
|                 Mode = 2, | |||
|                 origin = Vector(278.900513, -2033.692993, 516.067200), | |||
|                 GlowColor = "0 78 255 255" | |||
|             } | |||
|         }, | |||
|         [3] = { | |||
|             prop_dynamic = | |||
|             { | |||
|                 targetname = "crystal", | |||
|                 solid = 6, | |||
|                 renderfx = 15, | |||
|                 rendercolor = "255 255 255", | |||
|                 renderamt = 255, | |||
|                 physdamagescale = 1.0, | |||
|                 parentname = "crystal_spin", | |||
|                 modelscale = 1.3, | |||
|                 model = "models/props_moonbase/moon_gravel_crystal_blue.mdl", | |||
|                 MinAnimTime = 5, | |||
|                 MaxAnimTime = 10, | |||
|                 fadescale = 1.0, | |||
|          } |                 fademindist = -1.0, | ||
|      } |                 origin = Vector(278.900513, -2033.692993, 516.067200), | ||
| } |                 angles = QAngle(45, 0, 0) | ||
|             } | |||
|          }, | |||
|      }) | |||
| } | |||
| // ~15-25% faster for batch entity spawning | |||
| function Benchmark::PointScriptTemplate() { | |||
| script_template. |     local script_template = Entities.CreateByClassname("point_script_template") | ||
| script_template.AddTemplate(" |     script_template.AddTemplate("func_rotating", { | ||
|          message = "hl1/ambience/labdrone2.wav", | |||
|         volume = 8, | |||
|         targetname = "crystal_spin2", | |||
|          spawnflags = 65, | |||
|         solidbsp = 0, | |||
|         rendermode = 10, | |||
|         rendercolor = "255 255 255", | |||
|         vscripts = "rotatefix", | |||
|         renderamt = 255, | |||
|         maxspeed = 48, | |||
|         fanfriction = 20, | |||
|          origin = Vector(175.907211, -2188.908691, 516.031311), |          origin = Vector(175.907211, -2188.908691, 516.031311), | ||
|     }) | |||
| }) | |||
| script_template.AddTemplate(" |     script_template.AddTemplate("tf_glow", { | ||
|             target = "crystal2", | |||
|             Mode = 2, | |||
|             origin = Vector(175.907211, -2188.908691, 516.031311), | |||
|             GlowColor = "0 78 255 255" | |||
|     }) | |||
| }) | |||
|     script_template.AddTemplate("prop_dynamic", { | |||
|         targetname = "crystal2", | |||
|         solid = 6, | |||
|         renderfx = 15, | |||
|         rendercolor = "255 255 255", | |||
|         renderamt = 255, | |||
|         physdamagescale = 1.0, | |||
|         parentname = "crystal_spin2", | |||
|         modelscale = 1.3, | |||
|         model = "models/props_moonbase/moon_gravel_crystal_blue.mdl", | |||
|         MinAnimTime = 5, | |||
|         MaxAnimTime = 10, | |||
|         fadescale = 1.0, | |||
|         fademindist = -1.0, | |||
|         origin = Vector(175.907211, -2188.908691, 516.031311), | |||
|         angles = QAngle(45, 0, 0) | |||
|     }) | |||
|     script_template.AcceptInput( "ForceSpawn", null, null, null ) | |||
| } | |||
| </source> | </source> | ||
| Result: | Result: | ||
| Line 335: | Line 390: | ||
| |- | |- | ||
| |<code>SpawnEntityGroupFromTable</code> | |<code>SpawnEntityGroupFromTable</code> | ||
| |<code>0. | |<code>0.72ms</code> | ||
| |- | |- | ||
| |<code> | |<code>PointScriptTemplate</code> | ||
| |<code>0. | |<code>0.61ms</code> | ||
| |} | |} | ||
| = Iterating through players = | |||
| When iterating over all players in the map, it is generally not recommended to use FindByClassname on the [[player]] entity  | When iterating over all players in the map, it is generally not recommended to use FindByClassname on the [[player]] entity in high playercount environments (>8-12 players).  Iterating over the first <code>MaxClients</code> number of entindexes and grabbing the player from <code>PlayerInstanceFromIndex(i)</code> is notably faster and not much more complex to write in these circumstances.    | ||
| The performance of player iteration depends heavily on how many players are actively in the server.  In low playercount environments, the <code>PlayerInstanceFromIndex</code> approach is slower due to extra unnecessary iterations.  In high playercount environments, `FindByClassname` runs a more expensive loop on every entity in the map to find players. | |||
| If you want the fastest option at the cost of complexity, you should collect player entities in your own global table or array in an event such as player_team or player_activate, remove them on player_disconnect, then iterate over that when necessary.  Using a table gives you the added bonus of having a cache of player user IDs, which is faster to look up compared to reading the <code>player_manager</code> netprop. | |||
| {{warning|<code>player_activate</code> does not fire for tfbots!}} | |||
| == Benchmark == | |||
| The first script must be executed before the second one! | The first script must be executed before the second one! | ||
| {{todo|update benchmarks}} | |||
| <source lang=js> | <source lang=js> | ||
| :: | ::ALL_PLAYERS <- {} | ||
| ::Events <- { | ::Events <- { | ||
|      function OnGameEvent_player_team(params) |      function OnGameEvent_player_team(params) | ||
| Line 355: | Line 417: | ||
|          local player = GetPlayerFromUserID(params.userid) |          local player = GetPlayerFromUserID(params.userid) | ||
|          if  |          if ( player in ALL_PLAYERS ) return | ||
|          ALL_PLAYERS[ player ] <- params.userid | |||
|      } |      } | ||
| Line 364: | Line 426: | ||
|          local player = GetPlayerFromUserID(params.userid) |          local player = GetPlayerFromUserID(params.userid) | ||
|          if ( |          if ( !(player in ALL_PLAYERS) ) return | ||
|          delete ALL_PLAYERS[ player ] | |||
|      } |      } | ||
| } | } | ||
| Line 389: | Line 451: | ||
| } | } | ||
| foreach(player in  | foreach(player in ALL_PLAYERS.keys()) | ||
| { | { | ||
|      printl(player) |      printl(player) | ||
| Line 407: | Line 469: | ||
| |<code>0.0856ms</code> | |<code>0.0856ms</code> | ||
| |- | |- | ||
| |<code>Array iteration</code> | |<code>Array/Table iteration</code> | ||
| |<code>0.0679ms</code> | |<code>0.0679ms</code> | ||
| |} | |} | ||
| = Squirrel Performance Tips = | = Squirrel Performance Tips = | ||
| ==  | == Arrays and Tables == | ||
| Arrays in squirrel are, in practice, tables where the index is an integer value. | |||
| The .len() operator needs to first evaluate the data type (string or table/array), and uses a function call (expensive), we can avoid this overhead by directly checking the index. | |||
| <source lang=js> | |||
| /***************** | |||
|   * LENGTH CHECKS * | |||
|  *****************/ | |||
| function Benchmark::Len() { | |||
|     for ( local i = 0; i < 1000; i++ ) | |||
|         if ( arr.len() == 1000 ) | |||
|             local len = true | |||
| } | |||
| // ~40% faster, no _OP_PREPCALLK/_OP_CALL instructions | |||
| function Benchmark::Idx() { | |||
| for (local i = 0; i < 1000 |     for ( local i = 0; i < 1000; i++ ) | ||
|         if ( 999 in arr && !(1000 in arr) ) | |||
|             local len = true | |||
| } | |||
| </source> | </source> | ||
| Additionally, the integer 0 will return the value false in squirrel.  For specifically checking an empty array, this falsy evaluation is faster than directly checking if length equals 0 | Additionally, the integer 0 will return the value false in squirrel.  For specifically checking an empty array, this falsy evaluation is slightly faster than directly checking if length equals 0 | ||
| <source lang=js</code> | <source lang=js</code> | ||
| /**************************** | |||
|  * EMPTY ARRAY/TABLE CHECKS * | |||
|  ****************************/ | |||
| function Benchmark::LenExplicit() { | |||
| for (local i = 0; i < 1000 |     for ( local i = 0; i < 1000; i++ ) | ||
|         if ( arr.len() != 0 ) | |||
|             local len = true | |||
| } | |||
| // ~2-5% faster, no _OP_NE instruction | |||
| function Benchmark::LenFalsy() { | |||
|     for ( local i = 0; i < 1000; i++ ) | |||
|          if ( arr.len() ) | |||
|             local len = true | |||
| } | |||
| </source> | </source> | ||
| === Tables === | === Tables === | ||
| As shown above, we can circumvent the performance cost of .len() by using direct index look-ups where possible.  Instead of using .len(), We can  | As shown above, we can circumvent the performance cost of .len() by using direct index look-ups where possible.  Instead of using .len() for tables, We can create a helper class with a "length" member, and add/subtract from this whenever we insert/delete an item from the table. | ||
| <source lang=js> | <source lang=js> | ||
| // direct length index lookups instead of .len() calls. | |||
| Benchmark.NewTable <- class { | |||
|     _tbl   = null // the real table in our class | |||
|     length = 0 // length variable, static so other functions can't override it. | |||
| //insert stuff into the table and increment the table length |     constructor( tbl = null ) {  this._tbl = ( tbl || {} ) ; this.length = this._tbl.len() } | ||
| for (local i = 0; i <  | |||
|     function get(k) { _tbl[k] } | |||
|     function set(k, v) { k in _tbl ? _tbl[k] = v : (length++, _tbl[k] <- v) } | |||
|     function del(k) { ( length--, delete _tbl[k] ) } | |||
| } | |||
| local tab = Benchmark.NewTable() | |||
| local _tbl = tab._tbl | |||
| // insert stuff into the table and increment the table length | |||
| for (local i = 0; i <= 1000; i++) | |||
| { | { | ||
|      tab |      tab.set("value_" + i, i ) | ||
| } | } | ||
| //.len() eval | // .len() eval | ||
| for (local i = 0; i < 1000; i++) | function Benchmark::Len() { | ||
|     for (local i = 0; i < 1000; i++) | |||
|         print(_tbl.len() == 1000) | |||
| } | |||
| //index lookup | // index lookup, ~2.5% faster | ||
| for (local i = 0; i < 1000; i++) | function Benchmark::Length() { | ||
|     for (local i = 0; i < 1000; i++) | |||
|         print(tab.length == 1000) | |||
| } | |||
| </source> | </source> | ||
| This of course has performance implications of its own, and heavily depends on how often you are reading data from a table vs writing to it. | This of course has performance implications of its own, and heavily depends on how often you are reading data from a table vs writing to it.  You may only see performance benefits if you are checking table lengths a lot, but writing/reading infrequently | ||
| == Variable look-up and caching  | == Benchmark == | ||
| {| class="standard-table" | |||
| ! Configuration | |||
| ! Results | |||
| |- | |||
| |<code>Len</code> | |||
| |<code>0.075ms</code> | |||
| |- | |||
| |<code>Idx</code> | |||
| |<code>0.046ms</code> | |||
| |- | |||
| |<code>LenExplicit</code> | |||
| |<code>0.071ms</code> | |||
| |- | |||
| |<code>LenFalsy</code> | |||
| |<code>0.067ms</code> | |||
| |- | |||
| |<code>Len (table)</code> | |||
| |<code>9.4ms</code> | |||
| |- | |||
| |<code>Length (table)</code> | |||
| |<code>9.3ms</code> | |||
| |} | |||
| = Variable look-up and caching = | |||
| Squirrel will look for variables in the following order: | Squirrel will look for variables in the following order: | ||
| Line 480: | Line 598: | ||
| # root table | # root table | ||
| For example | For example: | ||
| # this will print the number 3 (outer local) | |||
| # commenting out <code>local thing1</code> will print 2 (const) | |||
| # commenting out <code>::thing1</code> would print 1 (root) | |||
| # uncommenting <code>local thing1 = 0</code> would print 0 (local) | |||
| <source lang=js> | <source lang=js> | ||
| Line 498: | Line 620: | ||
| <source lang=js> | <source lang=js> | ||
| ::SomeGlobalVar <-  | ::SomeGlobalVar <- 0 | ||
| function  | function Benchmark::_OnDestroy() { delete ::SomeGlobalVar } | ||
| function Benchmark::SlowIncrement()   | |||
| { | { | ||
|      for (local i =  |      for (local i = 1; i <= 1000; i++) | ||
|          SomeGlobalVar + |          SomeGlobalVar++ | ||
| } | } | ||
| function  | // 10x faster!? | ||
| function Benchmark::FastIncrement() | |||
| { | { | ||
|      local myvar = SomeGlobalVar |      local myvar = SomeGlobalVar | ||
|      for (local i =  | |||
|          myvar +=  |      for (local i = 1; i <= 1000; i++) | ||
|          myvar++ | |||
|     SomeGlobalVar = myvar | |||
| } | } | ||
| </source> | </source> | ||
| === Root table lookups === | === Root table lookups === | ||
| Prefixing a root-scoped variable with <code>::</code> will skip this traversal process and improve performance considerably. | |||
| <source lang=js> | <source lang=js> | ||
| :: | function Benchmark::NormalLookup() { | ||
|     for (local i = 1; i <= 1000; i++) | |||
|         SomeGlobalVar++ | |||
| } | |||
| // 10x faster!? | |||
| function Benchmark::RootLookup() { | |||
|      for (local i = 1; i <= 1000; i++) | |||
|      for (local i =  |          ::SomeGlobalVar++ | ||
|          :: | |||
| } | } | ||
| </source> | </source> | ||
| == Benchmark == | |||
| {{todo|this is the exact ''opposite'' result of the third-party benchmarking tool by a significant degree...?}} | |||
| {| class="standard-table" | |||
| ! Configuration | |||
| ! Results | |||
| |- | |||
| |<code>SlowIncrement</code> | |||
| |<code>0.591ms</code> | |||
| |- | |||
| |<code>FastIncrement</code> | |||
| |<code>0.021ms</code> | |||
| |- | |||
| |<code>NormalLookup</code> | |||
| |<code>0.584ms</code> | |||
| |- | |||
| |<code>RootLookup</code> | |||
| |<code>0.058ms</code> | |||
| |} | |||
Revision as of 10:44, 22 October 2025
This page includes tips and tricks for optimizing VScript performance.  All of these performance tests were done in  and many can be used in other
 and many can be used in other  -based titles.  Your mileage may vary in VScript supported games prior to the SDK update (
-based titles.  Your mileage may vary in VScript supported games prior to the SDK update (

 ).  Benchmarks figure come from this benchmarking tool.
).  Benchmarks figure come from this benchmarking tool.
 Warning:Only optimize your scripts if you need to!  Some of these tips may introduce extra unnecessary complexity to your projects.  Premature optimization without knowing where your performance issues actually come from is extremely ill-advised.
Warning:Only optimize your scripts if you need to!  Some of these tips may introduce extra unnecessary complexity to your projects.  Premature optimization without knowing where your performance issues actually come from is extremely ill-advised. Note:The built-in performance counter for VScript has a lot of "noise", and depends heavily on other things executing on the main game server thread.  Memory speed, CPU speed, And even file I/O, will greatly impact your results and the variance between them, even on repeated runs of the same code.  The numbers shown here are averages/ballpark figures taken from 5 or more repeated runs.  A third-party benchmarking tool does exist, however there is unfortunately no convenient download link for it.  Look around mapping/content creation discord servers for it.
Note:The built-in performance counter for VScript has a lot of "noise", and depends heavily on other things executing on the main game server thread.  Memory speed, CPU speed, And even file I/O, will greatly impact your results and the variance between them, even on repeated runs of the same code.  The numbers shown here are averages/ballpark figures taken from 5 or more repeated runs.  A third-party benchmarking tool does exist, however there is unfortunately no convenient download link for it.  Look around mapping/content creation discord servers for it.Folding
Functions
Folding functions in the context of VScript means folding them into the root table. This only needs to be done once on script load, and is recommended for functions that are commonly used.
Benchmark
 Note:Benchmark done on mvm_bigrock
Note:Benchmark done on mvm_bigrock/***********************************************************************************************************
 * FOLDING:                                                                                                *
 * Folding functions from their original scope into local/root scope is noticeably faster (~15-30%)        *
 * skips extra lookup instructions, also less verbose                                                      *
 ***********************************************************************************************************/
local GetPropString = NetProps.GetPropString.bindenv( NetProps )
local GetPropBool = NetProps.GetPropBool.bindenv( NetProps )
const MAX_EDICTS = 2048
function Benchmark::Unfolded() {
    for ( local i = 0, ent; i < Constants.Server.MAX_EDICTS; ent = EntIndexToHScript( i ), i++ ) {
        if ( ent ) {
            NetProps.GetPropString( ent, "m_iName" )
            NetProps.GetPropString( ent, "m_iClassname" )
            NetProps.GetPropBool( ent, "m_bForcePurgeFixedupStrings" )
        }
    }
}
// 20% faster, maybe more
function Benchmark::Folded() {
    for ( local i = 0, ent; i < MAX_EDICTS; ent = EntIndexToHScript( i ), i++ ) {
        if ( ent ) {
            GetPropString( ent, "m_iName" )
            GetPropString( ent, "m_iClassname" )
            GetPropBool( ent, "m_bForcePurgeFixedupStrings" )
        }
    }
}
Result:
| Configuration | Results | 
|---|---|
| Unfolded | 1.76ms | 
| Folded | 1.32ms | 
Constants
Similar to folding functions, folding pre-defined Constant values into the constant table (or the root table) increases performance significantly.
Benchmark
local _CONST = getconsttable()
// fold every pre-defined constant into the const table
if ( !( "ConstantNamingConvention" in ROOT ) )
	foreach( a, b in Constants )
		foreach( k, v in b )
            _CONST[k] <- v != null ? v : 0
setconsttable(_CONST)
function Benchmark::UnfoldedConst() {
    for (local i = 1; i <= Constants.Server.MAX_EDICTS; i++)
        local temp = i
}
function Benchmark::FoldedConst() {
    for (local i = 1; i <= MAX_EDICTS; i++)
        local temp = i
}
Result:
| Configuration | Results | 
|---|---|
| Unfolded | 0.356ms | 
| Folded | 0.033ms | 
Root table vs Constant table
Unlike values inserted into the root table, values inserted into the constant table are cached at the pre-processor level. What this means is, while accessing them is faster, it may not be feasible to fold your constants into the constant table if they are folded in the same script file that references them.
If you intend to insert values into the constant table (const keyword or getconsttable().foo <- "bar"), you must do this before any other scripts are executed, otherwise your script will not be able to read any values from it.
Benchmark
::SomeGlobalVar <- 0
const GLOBAL_VAR = 0x7FFFFFFF
function Benchmark::RootSetLookup() {
    for (local i = 1; i <= 10000; i++)
        local temp = ::SomeGlobalVar
}
// ~20-40% faster
function Benchmark::ConstSetLookup() {
    for (local i = 1; i <= 10000; i++)
        local temp = GLOBAL_VAR
}
Result:
| Configuration | Results | 
|---|---|
| Root | 0.267ms | 
| Const | 0.154ms | 
String Formatting
Squirrel supports two main ways to format strings: Concatenation using the + symbol, and the format() function.  format() is significantly faster than concatenation.
 Tip:For formatting entity handles and functions, use
Tip:For formatting entity handles and functions, use .tostring() and format it as a stringToKVString
the TOKVString() VScript function takes a Vector/QAngle and formats the values into a string.  For example, Vector(0, 0, 0).ToKVString() would be "0 0 0"
On top of being less cumbersome to write, ToKVString() is marginally faster than format().
However, when formatting multiple ToKVString() outputs into a new string, concatenation is faster due to less function calls.
Benchmark
function Benchmark::StringConcat() {
    for ( local i = 0; i < 10000; i++ )
        kvstring = mins.x + "," + mins.y + "," + mins.z + "," + maxs.x + "," + maxs.y + "," + maxs.z
}
function Benchmark::StringFormat() {
    for ( local i = 0; i < 10000; i++ )
        kvstring = format("%g,%g,%g,%g,%g,%g", mins.x, mins.y, mins.z, maxs.x, maxs.y, maxs.z)
}
function Benchmark::KVStringFormat() {
    for (local i = 0; i < 10000; i++ )
        kvstring = format("%s %s", mins.ToKVString(), maxs.ToKVString())
}
function Benchmark::KVStringConcat() {
    for (local i = 0; i < 10000; i++ )
        kvstring = mins.ToKVString() + " " + maxs.ToKVString()
}
Result:
| Configuration | Results | 
|---|---|
| StringConcat | 35.0847ms | 
| StringFormat | 23.0143ms | 
| KVStringFormat |  19.9377ms | 
| KVStringConcat | 18.3142ms | 
Spawning Entities
in VScript, there are four common ways to spawn entities:
- CreateByClassname + DispatchSpawn
- SpawnEntityFromTable
- SpawnEntityGroupFromTable
- point_script_template entity + AddTemplate
CreateByClassname + DispatchSpawn vs SpawnEntityFromTable
In general, performance is not a major concern when spawning entities. In special circumstances though, you may need to spawn and kill a temporary entity in an already expensive function. A notable example of an entity that would need this is trigger_stun. This entity will not attempt to re-stun the same player multiple times, so it is not possible to spawn a single entity and repeatedly fire StartTouch/EndTouch on the same target.
In situations like this, CreateByClassname + DispatchSpawn is roughly 4x faster in comparison to SpawnEntityFromTable.
Benchmark
local CreateByClassname = Entities.CreateByClassname.bindenv( Entities )
local SetPropBool = NetProps.SetPropBool.bindenv( NetProps )
local SetPropString = NetProps.SetPropString.bindenv( NetProps )
local DispatchSpawn = Entities.DispatchSpawn.bindenv( Entities )
// anywhere from 15-30% faster for single entity spawning
// The table passed to SpawnEntityFromTable needs to be interpreted and converted to something C++ can understand
// also, wide performance variations are likely due to garbage collection on the passed table
// meanwhile CreateByClassname/netprop/keyvaluefromstring are simple 1:1 C++ bindings
function Benchmark::ByClassname() {
    for (local i = 0; i < 100; i++) {
        local ent = CreateByClassname( "logic_relay" )
        DispatchSpawn( ent )
        SetPropString( ent, "m_iName", "__relay" )
    }
}
function Benchmark::FromTable() {
    for (local i = 0; i < 100; i++) {
        SpawnEntityFromTable( "logic_relay", { targetname = "__relay" } )
    }
}
Result:
| Configuration | Results | 
|---|---|
| SpawnEntityFromTable | 0.0428ms | 
| CreateByClassname | 0.0156ms | 
SpawnEntityGroupFromTable vs point_script_template
When spawning multiple entities at the same time, it is more efficient to use either SpawnEntityGroupFromTable or a point_script_template entity.  These options also have the added benefit of respecting parent hierarchy, so the parentname keyvalue works as intended.
point_script_template is both more flexible and faster. SpawnEntityGroupFromTable has several major limitations in comparison to point_script_template, and is generally not recommended. See the VScript documentation for more details on how to use point_script_template.
Benchmark
function Benchmark::EntityGroupFromTable() {
    // spawn origins are right outside of bigrock spawn
    SpawnEntityGroupFromTable({
        [0] = {
            func_rotating =
            {
                message = "hl1/ambience/labdrone2.wav",
                volume = 8,
                responsecontext = "-1 -1 -1 1 1 1",
                targetname = "crystal_spin",
                vscripts = "rotatefix", // see func_rotating vdc page for this
                spawnflags = 65,
                solidbsp = 0,
                rendermode = 10,
                rendercolor = "255 255 255",
                renderamt = 255,
                maxspeed = 48,
                fanfriction = 20,
                origin = Vector(278.900513, -2033.692993, 516.067200),
            }
        },
        [2] = {
            tf_glow =
            {
                targetname = "crystalglow",
                parentname = "crystal",
                target = "crystal",
                Mode = 2,
                origin = Vector(278.900513, -2033.692993, 516.067200),
                GlowColor = "0 78 255 255"
            }
        },
        [3] = {
            prop_dynamic =
            {
                targetname = "crystal",
                solid = 6,
                renderfx = 15,
                rendercolor = "255 255 255",
                renderamt = 255,
                physdamagescale = 1.0,
                parentname = "crystal_spin",
                modelscale = 1.3,
                model = "models/props_moonbase/moon_gravel_crystal_blue.mdl",
                MinAnimTime = 5,
                MaxAnimTime = 10,
                fadescale = 1.0,
                fademindist = -1.0,
                origin = Vector(278.900513, -2033.692993, 516.067200),
                angles = QAngle(45, 0, 0)
            }
        },
    })
}
// ~15-25% faster for batch entity spawning
function Benchmark::PointScriptTemplate() {
    local script_template = Entities.CreateByClassname("point_script_template")
    script_template.AddTemplate("func_rotating", {
        message = "hl1/ambience/labdrone2.wav",
        volume = 8,
        targetname = "crystal_spin2",
        spawnflags = 65,
        solidbsp = 0,
        rendermode = 10,
        rendercolor = "255 255 255",
        vscripts = "rotatefix",
        renderamt = 255,
        maxspeed = 48,
        fanfriction = 20,
        origin = Vector(175.907211, -2188.908691, 516.031311),
    })
    script_template.AddTemplate("tf_glow", {
            target = "crystal2",
            Mode = 2,
            origin = Vector(175.907211, -2188.908691, 516.031311),
            GlowColor = "0 78 255 255"
    })
    script_template.AddTemplate("prop_dynamic", {
        targetname = "crystal2",
        solid = 6,
        renderfx = 15,
        rendercolor = "255 255 255",
        renderamt = 255,
        physdamagescale = 1.0,
        parentname = "crystal_spin2",
        modelscale = 1.3,
        model = "models/props_moonbase/moon_gravel_crystal_blue.mdl",
        MinAnimTime = 5,
        MaxAnimTime = 10,
        fadescale = 1.0,
        fademindist = -1.0,
        origin = Vector(175.907211, -2188.908691, 516.031311),
        angles = QAngle(45, 0, 0)
    })
    script_template.AcceptInput( "ForceSpawn", null, null, null )
}
Result:
| Configuration | Results | 
|---|---|
| SpawnEntityGroupFromTable | 0.72ms | 
| PointScriptTemplate | 0.61ms | 
Iterating through players
When iterating over all players in the map, it is generally not recommended to use FindByClassname on the player entity in high playercount environments (>8-12 players).  Iterating over the first MaxClients number of entindexes and grabbing the player from PlayerInstanceFromIndex(i) is notably faster and not much more complex to write in these circumstances.  
The performance of player iteration depends heavily on how many players are actively in the server.  In low playercount environments, the PlayerInstanceFromIndex approach is slower due to extra unnecessary iterations.  In high playercount environments, `FindByClassname` runs a more expensive loop on every entity in the map to find players.
If you want the fastest option at the cost of complexity, you should collect player entities in your own global table or array in an event such as player_team or player_activate, remove them on player_disconnect, then iterate over that when necessary.  Using a table gives you the added bonus of having a cache of player user IDs, which is faster to look up compared to reading the player_manager netprop.
 Warning:
Warning:player_activate does not fire for tfbots!Benchmark
The first script must be executed before the second one!
::ALL_PLAYERS <- {}
::Events <- {
    function OnGameEvent_player_team(params)
    {
        local player = GetPlayerFromUserID(params.userid)
        
        if ( player in ALL_PLAYERS ) return
        ALL_PLAYERS[ player ] <- params.userid
 
    }
    
    function OnGameEvent_player_disconnect(params) 
    {
        local player = GetPlayerFromUserID(params.userid)
    
        if ( !(player in ALL_PLAYERS) ) return
        delete ALL_PLAYERS[ player ]
    }
}
__CollectGameEventCallbacks(Events)
::maxClients <- MaxClients().tointeger()
for (local player; player = Entities.FindByClassname(player, "player");)
{
    printl(player)
}
for (local i = 1; i <= maxClients; i++)
{
    local player = PlayerInstanceFromIndex(i)
    
    if (player == null) continue
    printl(player)
}
foreach(player in ALL_PLAYERS.keys())
{
    printl(player)
}
Result:
| Configuration | Results | 
|---|---|
| FindByClassname | 0.1289ms | 
| Index iteration | 0.0856ms | 
| Array/Table iteration | 0.0679ms | 
Squirrel Performance Tips
Arrays and Tables
Arrays in squirrel are, in practice, tables where the index is an integer value.
The .len() operator needs to first evaluate the data type (string or table/array), and uses a function call (expensive), we can avoid this overhead by directly checking the index.
/*****************
 * LENGTH CHECKS *
 *****************/
function Benchmark::Len() {
    for ( local i = 0; i < 1000; i++ )
        if ( arr.len() == 1000 )
            local len = true
}
// ~40% faster, no _OP_PREPCALLK/_OP_CALL instructions
function Benchmark::Idx() {
    for ( local i = 0; i < 1000; i++ )
        if ( 999 in arr && !(1000 in arr) )
            local len = true
}
Additionally, the integer 0 will return the value false in squirrel. For specifically checking an empty array, this falsy evaluation is slightly faster than directly checking if length equals 0
/****************************
 * EMPTY ARRAY/TABLE CHECKS *
 ****************************/
function Benchmark::LenExplicit() {
    for ( local i = 0; i < 1000; i++ )
        if ( arr.len() != 0 )
            local len = true
}
// ~2-5% faster, no _OP_NE instruction
function Benchmark::LenFalsy() {
    
    for ( local i = 0; i < 1000; i++ )
        if ( arr.len() )
            local len = true
}Tables
As shown above, we can circumvent the performance cost of .len() by using direct index look-ups where possible. Instead of using .len() for tables, We can create a helper class with a "length" member, and add/subtract from this whenever we insert/delete an item from the table.
// direct length index lookups instead of .len() calls.
Benchmark.NewTable <- class {
    _tbl   = null // the real table in our class
    length = 0 // length variable, static so other functions can't override it.
    constructor( tbl = null ) {  this._tbl = ( tbl || {} ) ; this.length = this._tbl.len() }
    function get(k) { _tbl[k] }
    function set(k, v) { k in _tbl ? _tbl[k] = v : (length++, _tbl[k] <- v) }
    function del(k) { ( length--, delete _tbl[k] ) }
}
local tab = Benchmark.NewTable()
local _tbl = tab._tbl
// insert stuff into the table and increment the table length
for (local i = 0; i <= 1000; i++)
{
    tab.set("value_" + i, i )
}
// .len() eval
function Benchmark::Len() {
    for (local i = 0; i < 1000; i++)
        print(_tbl.len() == 1000)
}
// index lookup, ~2.5% faster
function Benchmark::Length() {
    for (local i = 0; i < 1000; i++)
        print(tab.length == 1000)
}
This of course has performance implications of its own, and heavily depends on how often you are reading data from a table vs writing to it. You may only see performance benefits if you are checking table lengths a lot, but writing/reading infrequently
Benchmark
| Configuration | Results | 
|---|---|
| Len | 0.075ms | 
| Idx | 0.046ms | 
| LenExplicit | 0.071ms | 
| LenFalsy | 0.067ms | 
| Len (table) | 9.4ms | 
| Length (table) | 9.3ms | 
Variable look-up and caching
Squirrel will look for variables in the following order:
- local variables
- "outer" local variables (locals that are in parent scope)
- constants
- root table
For example:
- this will print the number 3 (outer local)
- commenting out local thing1will print 2 (const)
- commenting out ::thing1would print 1 (root)
- uncommenting local thing1 = 0would print 0 (local)
::thing1 <- 1
const thing1 = 2
local thing1 = 3
::GetThing1 <- function() {
    // local thing1 = 0
    return thing1
}
print( GetThing1() )
Traversing scopes to find variables like this will negatively impact performance. It is better to cache variables as locals before expensive loops or fast-firing functions (thinks).
::SomeGlobalVar <- 0
function Benchmark::_OnDestroy() { delete ::SomeGlobalVar }
function Benchmark::SlowIncrement() 
{
    for (local i = 1; i <= 1000; i++)
        SomeGlobalVar++
}
// 10x faster!?
function Benchmark::FastIncrement()
{
    local myvar = SomeGlobalVar
    for (local i = 1; i <= 1000; i++)
        myvar++
    SomeGlobalVar = myvar
}
Root table lookups
Prefixing a root-scoped variable with :: will skip this traversal process and improve performance considerably.
function Benchmark::NormalLookup() {
    for (local i = 1; i <= 1000; i++)
        SomeGlobalVar++
}
// 10x faster!?
function Benchmark::RootLookup() {
    for (local i = 1; i <= 1000; i++)
        ::SomeGlobalVar++
}
Benchmark
| Configuration | Results | 
|---|---|
| SlowIncrement | 0.591ms | 
| FastIncrement | 0.021ms | 
| NormalLookup | 0.584ms | 
| RootLookup | 0.058ms |