Enums



  • Should I use enums or is it more efficient to use a const var object or reg variable?


  • administrators

    Use const variables in combination with a namespace. Accessing this is as just as fast as using the actual literal value; everthing else comes with a performance penalty

    namespace Direction
    {
        const var UP = 0;
        const var DOWN = 1;
        const var BOTH = 2;
    };
    
    // Usage:
    switch(d)
    {
       case Direction.UP:
    


  • Yeah I thought there would be a penalty. What about using enums within a namespace? Since we can't nest namespaces.


  • administrators

    If you're already in a namespace, you can just use const variables - a common rule is to write constant values and enums LIKE_THIS so you don't get confused 🙂



  • How does const var Direction = {UP:0, DOWN:1, BOTH:2}; compare for efficiency to using individual const vars?


  • administrators

    You can profile this easily to measure the difference:

    const var DirectionSlow = { "UP": 0, "DOWN": 1, "UP_DOWN": 2};
    
    namespace DirectionFast
    {
    	const var UP = 0;
    	const var DOWN = 1;
    	const var UP_DOWN = 2;
    };
    
    
    reg i = 0;
    
    Console.print("");
    Console.print("Object Access:");
    
    Console.start();
    
    for(i = 0; i < 1000000; i++)
    {
    	// Use many accesses to diminish the impact of the loop logic
    	DirectionSlow.UP_DOWN;
    	DirectionSlow.UP;
    	DirectionSlow.DOWN;
    	DirectionSlow.UP_DOWN;
    	DirectionSlow.UP;
    	DirectionSlow.DOWN;
    	DirectionSlow.UP_DOWN;
    	DirectionSlow.UP;
    	DirectionSlow.DOWN;
    }
    		
    Console.stop();
    
    Console.print("Namespace Access:");
    
    Console.start();
    
    for(i = 0; i < 1000000; i++)
    {
    	Direction.UP_DOWN;
    	Direction.UP;
    	Direction.DOWN;
    	Direction.UP_DOWN;
    	Direction.UP;
    	Direction.DOWN;
    	Direction.UP_DOWN;
    	Direction.UP;
    	Direction.DOWN;
    }
    	
    Console.stop();
    

    On my system it's 540ms vs 387ms. It's not super critical, but if possible I'd recommend using namespaces.



  • Thank you


Log in to reply
 

1
Online

339
Users

1.0k
Topics

7.1k
Posts

Looks like your connection to Forum was lost, please wait while we try to reconnect.