Global variables or Local variables
#1

hmm.. I just was thinking what's better?
And what's more efficent
Reply
#2

I use locals variables, I don't know if a global variable could cause errors, becouse someones say that pawno is single-threaded (it is..) and shouldn't happen anything, but others say that it could happend that the variable get a wrong value, so thats why I use local.
Reply
#3

I'd recommend globals. Some people think it's a bad idea but I've had no repercussions.

Some speed tests:

pawn Code:
new
    g_String[128];

GetString()
{
    g_String = "just returning this here folks";
    return g_String;
}

_GetString()
{
    new
        string[128];
    string = "just returning this here folks";
    return string;
}


public OnGameModeInit()
{
    new
        t,
        string[128];
    for (new x; x < 10; ++x)
    {
        t = GetTickCount();
        for (new i; i < 1000000; ++i)
        {
            string = GetString();
        }
        printf("global: %i ms", GetTickCount() - t);
        t = GetTickCount();
        for (new i; i < 1000000; ++i)
        {
            string = _GetString();
        }
        printf("local: %i ms", GetTickCount() - t);
    }
    return 1;
}
Code:
[11:43:12] global: 828 ms
[11:43:14] local: 1216 ms
[11:43:14] global: 770 ms
[11:43:16] local: 1203 ms
[11:43:16] global: 777 ms
[11:43:18] local: 1243 ms
[11:43:18] global: 782 ms
[11:43:20] local: 1156 ms
[11:43:20] global: 797 ms
[11:43:22] local: 1167 ms
[11:43:22] global: 738 ms
[11:43:23] local: 1152 ms
[11:43:24] global: 743 ms
[11:43:25] local: 1160 ms
[11:43:26] global: 749 ms
[11:43:27] local: 1148 ms
[11:43:28] global: 756 ms
[11:43:29] local: 1182 ms
[11:43:30] global: 758 ms
[11:43:31] local: 1251 ms
Reply
#4

These tests really don't matter. You're never doing any looping like this, so your benchmark doesn't resemble real world testing. Local and global variables both have their place in almost every language. This question is born out of ignorance. Remember the first rule of optimizing is, don't optimize until your code is slow. You need to be writing legible clear code above all else. If that code runs slow, then you need to benchmark and review your alternatives. Premature optimization is the root of all evil.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)