Code Sizer

From Second Life Wiki
Revision as of 16:56, 19 October 2007 by Ppaatt Lynagh (talk | contribs) (answer Q: Want to know how small that code is?)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

How Small Is That Code

Q: Want to know how small that code is?

A: The most accurate, least misleading technique we have found is as follows.

First compile & run this brief & clear & conventional (though neither fast nor small) script:

// http://wiki.secondlife.com/wiki/Talk:LSL_Script_Efficiency

integer unspent = 16384; // the well-known available size of byte code plus heap plus stack
integer wasted = 313; // the well-known byte size of this script before you add source code to it

// Count the bytes newly occupied by new byte code when you added source code to this script.

integer getSpentBytes(integer spendable)
{
    return spendable - llGetFreeMemory();
}

// Print the bytes spent when you added code to this script,
// whenever you Save or Reset this script.

default
{
    state_entry()
    {
        llOwnerSay((string) getSpentBytes(unspent - wasted));
    }
}

The integer zero should be the result printed when you first try this.

See how that works?

This code quotes the well-known available size of byte code plus heap plus stack. This code quotes the well-known size of itself. This code calculates the difference between those two quotes, i.e., the count of bytes that should be free until you add more code. This code prints zero so long as those well-known sizes do not change (and prints zero in the unlikely test case of the change in wasted exactly canceling out the change in unspent).

Now you add code, and run the script again. For example, suppose you create a second copy of the getSpentBytes routine, giving its name some otherwise unused spelling like getSpentBites. Then you will see the second copy costs 47 bytes. A third copy costs the same, another 47 bytes for a total of 94 bytes. And so on.

Get it?

Now you can easily & instantly measure how small any code is.

Note: Take care to avoid falling into the easy error of printing llGetFreeMemory() before and after you delete the last function of the script. Adding the first function to the script costs an extra 4 bytes. Only people who understand LSO know why, and they haven't yet published that explanation anywhere near here.