Raised This Month: $ Target: $400
 0% 

Memory Usage Optimizing, static and new


  
 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
SonicSonedit
Veteran Member
Join Date: Nov 2008
Location: Silent Hill
Old 05-07-2011 , 17:04   Re: Memory Usage Optimizing, static and new
Reply With Quote #2

New allocates memory for new variable, sets allocated memory to 0's and then, after function is over, frees memory (destroyes variable). It does so every time function is called.
Static allocates memory just once and keeps variable.
If your function is used often or you allocate big amount of data (and function is used more than at least once) its wiser to use static.
If your function isn't used often it's better to use new, so memory used by variables from your function, when function done executing will be freed.

I don't know about pawn, but using new in extremly oftenly called functions will cause memory fragmentation in some languages, not to mention perfomance reduction. On other hand, the more static you use, the more memory your plugin will use for sure.
I prefer to go with static in most cases.

Here is small example. Like in regular functions, variables declared in for(){} statement are destroyed after statement done executing:
PHP Code:
#include <amxmodx>
#include <amxmisc>

#define PLUGIN "New Plug-In"
#define VERSION "1.0"
#define AUTHOR "author"


public plugin_init()
{
    
register_plugin(PLUGINVERSIONAUTHOR)
    
    
// Add your code here...
    
    
for (new i=0;i<100;i++)
        
server_print("\n%d",i)
        
    
server_print("%d",i// You will get Error: Undefined symbol "i" on line 17, because "i" is already freed (destroyed)

The only difference between for(){} and regular functions is that you can't use static in it. Same goes for while (){} statement.
__________________


Last edited by SonicSonedit; 05-07-2011 at 17:14.
SonicSonedit is offline
 



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 04:27.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode