|
Memory Allocation for Procedures |
Top Previous Next |
Variable memory (RAM) allocation in TiOS is not dynamic. Memory is allocated for variables at compile-time.
The compiler builds a "tree" reflecting procedure calls within your project. When two different procedures never call each other, it is safe to allocate the same memory space for the variables of each of them. They will never get mixed.
Let us say we have two event handlers in our project: on_event_1, which needs 7 bytes of memory, on_event_2, which needs 5 bytes of memory. They do not call each other. In this case, the total memory required for our project will be 7 bytes -- they will share the same memory space because only one will be executing at any given time.
However, sometimes procedures call other procedures. This affects memory allocation.

As seen above, the event handler on_event_1 calls procedure A, which in turn calls procedure B. The memory required for each procedure is listed in brackets. Since on_event_1, procedure A and procedure B call each other, they may not share the same memory space. If procedure A keeps a variable in memory, then obviously procedure B cannot use the same space in memory to store its own variables, because procedure A may need its variable once control returns to it after procedure B has completed. Thus, the total memory required for this tree is 11 bytes.
Now, let us say we also have on_event_2 in our project, which calls procedure C, which in turn calls procedure D. This is a completely separate chain:

As can be seen, this chain takes up 7 bytes of memory. However, this memory can be the same memory used for the on_event_1 chain, because these two chains will never execute at the same time. Thus, the total memory required for our project remains at 11 bytes.
A typical project usually includes a number of global variables. Naturally, these variables are allocated their exclusive space that is not shared with local variables of procedures. Variables of HTML scope, which are local by nature, are allocated exclusive memory space as if they were global (this is an unfortunate byproduct of the way compiler handles HTML pages). Hence, it is more economical to implement necessary functionality in procedures invoked from HTML pages rather than include BASIC code directly into the body of HTML files.