- Joined
- Nov 20, 2005
- Messages
- 1,156
vJass script for substantially increasing the speed of looping through integers (gets inlined by JassHelper).
Example use:
Example use:
JASS:
function X takes nothing returns nothing
local integer i = 0
loop
set i = Increment(i)
// Do something here.
exitwhen i>=100
endloop
// Something will have been done 100 times.
endfunction
JASS:
library ForLoopHelper
//*********************************************************************
//* ForLoopHelper
//* ----------
//*
//* This library has been designed to improve the performance of for
//* loops. Whenever you would normally use "set i=i+1" in a loop,
//* replace it with "set i=Increment(i)". Likewise, "set i=i-1" can be
//* replaced with "set i=Decrement(i)". The two functions get inlined
//* resulting in a simple array read, which is 12% faster than adding
//* or subtracting 1 to/from the variable i.
//*
//* The obvious limitation here is that the value being incremented
//* must not be smaller than 0 or larger than 8190 and it can only be
//* incremented or decremented by 1, but this should be enough to
//* cover nearly all for loops.
//*********************************************************************
globals
// This determines how many indexes will be initialized and affects loading time.
// The number has to be larger than the longest for loop that uses this library.
// This number may not be larger than 8190, since that is the maximum array size.
private constant integer MAX_INDEX = 8190
endglobals
//=====================================================================
private module Initialization
static method onInit takes nothing returns nothing
local integer i=0
local integer j
loop
exitwhen i>MAX_INDEX
set j=i+1
set .next[i]=j
set .prev[j]=i
set i=j
endloop
set .prev[0]=-1
endmethod
endmodule
private struct Inc extends array
static integer array next
static integer array prev
implement Initialization
endstruct
//=====================================================================
function Increment takes integer i returns integer
debug if i<0 or i>8190 then
debug call BJDebugMsg("Increment error: The integer being incremented must not be less than 0 or more than "+I2S(MAX_INDEX)+".")
debug return i+1
debug endif
return Inc.next[i]
endfunction
function Decrement takes integer i returns integer
debug if i<0 or i>8190 then
debug call BJDebugMsg("Decrement error: The integer being decremented must not be less than 0 or more than "+I2S(MAX_INDEX)+".")
debug return i-1
debug endif
return Inc.prev[i]
endfunction
endlibrary
Last edited by a moderator: