clugg / sm-json

A pure SourcePawn JSON encoder/decoder.
GNU General Public License v3.0
82 stars 8 forks source link

Some optimization #18

Closed MAGNAT2645 closed 3 years ago

MAGNAT2645 commented 3 years ago

You should cache values for loop condition.

For example:

    public int IndexOf(any value)
    {
        any current;
        for (int i = 0; i < this.Length; i += 1) {
            if (this.GetValue(i, current) && value == current) {
                return i;
            }
        }

        return -1;
    }

    public int IndexOfString(const char[] value)
    {
        for (int i = 0; i < this.Length; i += 1) {
            if (this.GetKeyType(i) != JSON_Type_String) {
                continue;
            }

            int current_size = this.GetKeyLength(i) + 1;
            char[] current = new char[current_size];
            this.GetString(i, current, current_size);
            if (StrEqual(value, current)) {
                return i;
            }
        }

        return -1;
    }

for (int i = 0; i < this.Length; i += 1) { should be replaced with

        int iLength = this.Length;
        for (int i = 0; i < iLength; i += 1) {

Stack allocation is cheap afaik so it would be better to store values that are often compared in loops.

clugg commented 3 years ago

Thanks for the suggestion! I have just released v3.2.1 which optimises any places in the code where object length is read more than once.