[TUT] The Use of Static Variables
What is a static variable? It is basically a global variable that can only be accessed by the function it is declared in.
This means that: Code:
Is NOT valid. Why? Because the static variable was declared in fnDoFunc, not plugin_init. The example above does not exemplify the true power of static variables. If you're just going to zero it before you use it, use the operator "new". Declaring a new variable is not an expensive operation, simply the zeroing of it is. But what can a static variable do? Here's an example of the usage of a static variable vs. a new variable: Static Code:
New Code:
But why is the static version faster? Because the memory isn't created every single time it's needed, rather it's left there, kind of like a global variable never loses its value ever after being used in a function. So for example, take in this hypothetical sequence of events in a server: Static Code:
static variable initialized Code:
Hawk552 joins server |
Re: The Use of Static Variables
Thanks for the info. BTW: Happy Birthday.
|
Re: The Use of Static Variables
hmmm interesting...
Can you tell me when to use it and when not to use it |
Re: The Use of Static Variables
Quote:
Code:
You'd might as well use new, because the = 0 section of it will make it the same expensiveness as using new. This goes for most other things like = get_user_frags(id) etc. When using a huge ass array like a motd or menu it's generally best to use static because arrays are a huge hit on CPU, and making it static nullifies that. You must be careful about re-entrancy though, as in something being set from the last time it was used and using it for this instance anyway. If your script is enormous you might start running out of memory in which case you can use #pragma dynamic, with some value like 131072 (which is in bytes) But as shown in my example one of the best ways to use this is something like: Code:
|
Re: The Use of Static Variables
Quote:
All of which are very demanding forwards, so a static would be handy to reduce overhead in the long term. One annoying thing with static is that you cannot assign as you can with new, example: Code:
new team = get_user_team(id) Code:
static team, player |
Re: The Use of Static Variables
Quote:
|
Re: The Use of Static Variables
Using static isn't really necessary if you initialize it like that. It's more appropriate for arrays.
|
Re: The Use of Static Variables
Quote:
|
Re: The Use of Static Variables
Quote:
|
Re: The Use of Static Variables
oh, hello pm,
maybe you should make a tutorial on the use of static variables instead :up: |
All times are GMT -4. The time now is 09:14. |
Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.