Board index » delphi » Stack manipulation and local variables
Mattias Andersson
Delphi Developer |
Stack manipulation and local variables2006-08-11 02:19:23 AM delphi205 Hi all, I have a performance critical routine in which I need to use a temporary buffer. The size of the buffer can vary, so it would make sense to use a dynamic array. However, by using a dynamic array, memory would have to be allocated/deallocated within the routine itself (and consequently it would degrade performance). One option would be to preallocate the memory in a global variable. This would, however, cause problems in multithreaded applications, since multiple threads could then update the same memory. I need to ensure that the routine is thread-safe, so I want to avoid this kind of memory conflicts. Also I don't want to use critical sections, since that would degrade performance as well. A possible solution would be to dynamically grow the stack upon entering the procedure. We could then use the extra stack space to store the buffer. I considered the following implementation: procedure Test(Size: Integer); var I: Integer; P: PByteArray; // temporary buffer begin asm SUB ESP,Size MOV P,ESP end; ... for I := 0 to Size - 1 do P[I] := I; ... end; This seems to work well (assuming the stack is decreased by a multiple of 4). Does anyone know if this approach is reliable? Could it have any undesirable side-effects? TIA, Mattias |