Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (475)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (530)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  using variables vs straight up numbahs...  (Read 4656 times)
0 Members and 1 Guest are viewing this topic.
Offline ~Spaceaholic

Senior Member


Medals: 3
Projects: 1



« Posted 2011-10-23 16:30:34 »

There are many many places within a game I am developing (Tentatively called: Gulp), where I have straight up numbahs plugged into my code as apposed to using a variable that would stay around... I plan on changing this once I work out all the kinks but was wondering what kind of performance difference I could expect to see... right now I draw anywhere from 10-150 sprites to the screen and there offsets into the sprite sheet as well as the dimentions of the final image are straight up numbers, so thats 4 integers per item drawn...

So I guess my real question is how more efficient is it to aces a local integer as apposed to having the number passed in on the fly.... heres an example of a single draw, the underlying code behind the method call creates a source and destination Rect to use as a mask to draw the sprite to a canvas....

g.drawPixmap(Assets.fishLeft7, drawX - (Assets.fishLeft7.getHeight()/2), drawY- (Assets.fishLeft7.getHeight()/2) , fish.sprite* 192, 0,192,86);

If you need me to clarify this, just ask, and Ill try... thanks...
Offline pjt33
« Reply #1 - Posted 2011-10-23 17:55:30 »

If you replace them with static final fields then the compiler will inline them directly, and the only difference will be that the class gets a tiny bit larger. If you're using an obfuscator then there will be no difference at all from the point of view of the final bytecode - although the source code will be more maintainable.
Offline ~Spaceaholic

Senior Member


Medals: 3
Projects: 1



« Reply #2 - Posted 2011-10-23 18:07:10 »

I am still very green to the ways of programming, and do not fully understand your response...

what is an obfuscator?

it is my understanding(very possible I am wrong) that by NOT having variables which hold the values I need, and by simply having the raw number in my code that the machine will have to create the number each time it is seen, and therefore every loop through the draw method, whereas if I already have a variable allocated then all it needs to do is access the variable... is this true? and what is the speed difference if any?

thanks...

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #3 - Posted 2011-10-23 19:12:18 »

There is no speed difference between a hard-coded magic number and a named constant. So just do it the proper/cleaner way and save yourself a whole bunch of annoying bugs.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline pitbuller
« Reply #4 - Posted 2011-10-23 19:34:33 »

Computers are fast nowadays. First learn how to make cleanest and simplest code possible. After many years you can start do micro optimization but only if you know what are you doing and can you measure the difference.

So don't stress about performance while you aren't sure what is important and what not.
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #5 - Posted 2011-10-24 00:33:18 »

Premature optimizations are the root of all evil. [tm]

Offline sproingie

JGO Kernel


Medals: 201



« Reply #6 - Posted 2011-10-24 03:50:13 »

This particular case of hardwired magic numbers vs static final fields isn't even a matter of "optimization", it's "the resulting code will be exactly the same".
Offline ~Spaceaholic

Senior Member


Medals: 3
Projects: 1



« Reply #7 - Posted 2011-10-26 13:01:17 »

thank you for your responses, I have been looking for ways to optimize my code for a couple weeks now and I guess the journey is not over yet...
although computers are exceptionally fast, my application will be running on android devices, some with well under 1ghz speeds, so some optimization is needed, either that or I need to drop some of my preexisting effects...

heres another question for you:
right now I have my arraylists of creatures owned by a class as public variables, right now I am iterating over the list 3 different times, once to update positions, once to check collisions, and then again to draw all the objects... the way I have it set up I could consolidate the collision detection into the update method, which would eliminate one iteration.... now if I was to run the same exact collision detection code within the update creature iteration I would be fetching each creature object half as often, Should I expect to see any optimization this way?

heres some quick sudo code of what I mean:

current:

Creature creature;
Loop over CreatureObjects
    creature = Creatures.get(i)
    update positions and behaviors(creature)

Creature creature;
Rect enemy;
Loop over CreatureObjects
    creature = Class.Creatures.get(i)
    enemy = new Rect() sized and positioned accordingly
    check collision with user rect

new way:

Creature creature;
Rect enemy;
Loop over CreatureObjects
    creature = Class.Creatures.get(i)
    creature.update positions and behavior()
    enemy = new Rect() sized and positioned accordingly
    check collision with user rect

     
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #8 - Posted 2011-10-26 13:28:13 »

Have you profiled your code? If not then you're wasting your time. Three iterations over the creatures list is highly unlikely to be causing performance issues.

Profile your code and find out where your game is *really* spending it's time. Good places to look would be your core drawing routines.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline zendar

Senior Newbie




Go Java!


« Reply #9 - Posted 2011-10-26 13:56:07 »

Just write the code in the cleanest way possible and worry about performance later on. For 95% of your codebase maintenance is more important than performance.

If you want to care about performance, you should be caring about what algorithms you are using. This is where the "premature optimization is the root of all evil" quoters sometimes it wrong. Performance should be considered early on in the sense of "how should things be done / what algorithms should we use", and not in the sense of "how do I optimize this loop".

TLDR; Use variables/constants for your magic numbers. :-)


Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline cylab

JGO Ninja


Medals: 38



« Reply #10 - Posted 2011-10-26 15:04:01 »

This is where the "premature optimization is the root of all evil" quoters sometimes it wrong.
premature != early Wink

Mathias - I Know What [you] Did Last Summer!
Offline Roquen
« Reply #11 - Posted 2011-10-26 15:35:18 »

The quote is totally wrong.  It should read: "Premature coding is the root of many disasters".

Premature optimization is an oxymoron..it doesn't exist.
Offline counterp

Senior Member


Medals: 11



« Reply #12 - Posted 2011-10-26 15:44:09 »

how is that an oxymoron?
Offline zendar

Senior Newbie




Go Java!


« Reply #13 - Posted 2011-10-26 15:53:08 »

The quote is totally wrong.  It should read: "Premature coding is the root of many disasters".

Premature optimization is an oxymoron..it doesn't exist.

The quote is from Donald Knuth and goes like this: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" (source: Wikipedia)

I wouldn't call it an oxymoron. You can have code written that should not be optimized until you know if it needs optimization or not. Sometimes you might think think it is in need of optimization and later on find out that it is ok. I don't see an oxymoron there. Smiley
Offline Roquen
« Reply #14 - Posted 2011-10-26 16:05:19 »

By def optimization is attempting to meet a specific goal with a given metric (by max/minimizing the measure).  If you're prematurely coding anything then you cannot have a well defined goal and measure (even if you think that you do).  So premature optimization does not exist.  So, as an example, if one spends time increasing the speed of some chuck of code that never in any time window consumes any significant CPU time, then that programmer is by definition performing a sub-optimal task (wasting the resource of programming time).

Knuth is a god of CS.  But he's never been concerned with RT issues.  Many rules of thumb that apply to other fields of CS get thrown out the window.  Of course this is true of many "rules of thumb" in many specific sub-fields.
Offline sproingie

JGO Kernel


Medals: 201



« Reply #15 - Posted 2011-10-26 17:28:55 »

I'm pretty sure readers of Knuth are familiar enough with colloquial language to implicitly prefix "attempts at" before the word "optimization".  You say it yourself when you say optimization is attempting to meet a specific goal (though I would argue that goal is often as nebulously nonspecific as "go faster").   Not all active verbs require a successful outcome on the target: I could assault a brick wall with a pillow, but I could not be said to damage it.  One requires merely an action, the other a change in state.  This could get deeply philosophical, but I suspect it's really just grammar (paging Herr Wittgenstein...)
Offline JL235

JGO Coder


Medals: 10



« Reply #16 - Posted 2011-10-26 19:38:47 »

By 'premature' I think what Knuth really means is 'when it is not needed'. Lots of programmers spend hours/days/weeks working on optimizations which will have no real effect on the resulting code.

Static final fields can be redefined at runtime using reflection, and they can be accessed before any value is set to them, so the JVM can't automatically switch them out when it parses the bytecode. This is especially true for constants that hold references to objects and classes, since you don't know what you are making an instance of, until that class is loaded (the class could even be generated on the fly, or heavily modified, when the JVM goes to look for it). You can also load the same class multiple times, allowing the same static final variables to exist multiple times, which could hold entirely different values.

There are theoretical strategies that could work around these, allowing static final fields be much faster then standard non-static and non-final fields, or for them to be removed entirely. But for the reasons above, I would be dubious that all JVM's automatically replace 'MY_CONSTANT' with it's literal value in the resulting assembly. Although mature JVM's like HotSpot almost certainly do work to optimize static final fields.

But if we presume the worst case, where they aren't optimized out, what would be performance overhead be? At worst, I would expect they would cost a microsecond or two, per frame. This is so small, it would be difficult to prove it even exists!

Ultimately just remember: if people cannot notice the improvement your optimization brings, then it was pointless.

Offline Riven
« League of Dukes »

JGO Overlord


Medals: 742
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #17 - Posted 2011-10-26 19:52:47 »

static final constants are replaced by the compiler not necessarily the JIT. If you change the value of the final field, you end up with parts of the application using the new value and parts that 'use' the old value (because there isn't any GETSTATIC left in the bytecode). Even if there is a GETSTATIC instruction in the bytecode, HotSpot can deem it optimizable and might replace the instruction with a constant. The effects can be read here



Hence: you really shouldn't as both the compiler and the JIT will make this grey area a huge mess.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline sproingie

JGO Kernel


Medals: 201



« Reply #18 - Posted 2011-10-26 21:29:14 »

While the discussion about the unexpected effects of reflection disobeying access restrictions is pretty fascinating on its own, we probably shouldn't derail the thread into the finer points of the Java Memory Model Smiley

Long story short: magic numbers bad, symbolic constants good Smiley
Offline Karmington

Senior Member


Medals: 1
Projects: 1


Co-op Freak


« Reply #19 - Posted 2011-10-27 00:30:43 »

And, to find out where you need optimization:
I usually do a pretty crude method of placing timers around draw and update and first measure those. Draw should be taking most of the space in most games. Then putting timers around the major blocks of stuff, sniffing for areas that are causing big hits to performance ( taking longer to execute ). Once say 4+ sectors are timed you can make an educated guess at where the stress is.

Offline sproingie

JGO Kernel


Medals: 201



« Reply #20 - Posted 2011-10-27 00:48:13 »

Just run under a profiler.  No changes to code, no need to guess.

Offline ~Spaceaholic

Senior Member


Medals: 3
Projects: 1



« Reply #21 - Posted 2011-10-27 02:56:04 »

Thanks again for your responses... at least now I am looking in the right areas... I ran some test and on average my drawing time to update time ratio was about 25 to 1 peaking around 40 to 1 and dropping as low as 18 to 1.... I also did a little more digging to find out that the main culprits are my background which is composed of 3 large images which each have transparent areas... the background currently consumes about half the drawing time, so how do we fix it?

a quick intro to my game:
you control a creature eating other creatures within a world
the world is 800x1600px
the user can move to the edge of the world and the background offsets accordingly

my background is composed of three layers with dimentions of 800x90 800x246 and 800x229 they are drawn using a scaling matrix to double this size

theMatrix.reset();
theMatrix.postScale(1.35f, 2);
theMatrix.postTranslate(-world.offsetX * .35f, -world.offsetY * .35f);
g.drawPixmap(Assets.sky, theMatrix);

theMatrix.reset();
theMatrix.postScale(2, 2);
theMatrix.postTranslate(-world.offsetX, -world.offsetY + world.worldHeight - (Assets.ground.getHeight()*2));      
g.drawPixmap(Assets.ground, theMatrix);

what would you suggest I do? I would really like to use these images, they add so much to the game, but if there is not a way to at least halve the time spend drawing them I will likely have to dispose of them and adopt a new background system....
Offline loom_weaver

JGO Coder


Medals: 17



« Reply #22 - Posted 2011-10-27 04:19:52 »

I hope you aren't scaling every frame i.e. every paint...
Offline counterp

Senior Member


Medals: 11



« Reply #23 - Posted 2011-10-27 05:33:36 »

Premature - happening, arriving, existing, or performed before the proper, usual, or intended time

Optimization - an act, process, or methodology of making something (as a design, system, or decision) as fully perfect, functional, or effective as possible

those were the Webster definitions.

combine them, you get

Premature optimization - Performing the act of making something as fully perfect, functional, or effective as possible, before the proper or usual time

(the proper or usual time in this case is when it becomes necessary, and for something as small as this it will probably never be necessary, but premature optimization can apply to even the most complex of systems and not just a small change like magic numbers vs constants)

where's the oxymoron in that?
Offline Roquen
« Reply #24 - Posted 2011-10-27 07:33:35 »

Webster's and CS defs aren't always the same are they?  If they were then all computer languages are functional languages.
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #25 - Posted 2011-10-27 09:51:04 »

my background is composed of three layers with dimentions of 800x90 800x246 and 800x229 they are drawn using a scaling matrix to double this size
Split the background up into small-ish tiles (say, 64x64), and store the background in a tile array. When drawing, use the current camera coords to index into the array and only draw the tiles that are actually on screen. Big fat images where 90% of them aren't on screen are usually terribly inefficient.

And as already mentioned, don't scale them at run time, scale them at load time or compile time if possible.

Edit: what API is that? I'd suspect that drawPixmap() with a matrix argument is probably the slowest way to draw as it'll have to fall back to a very general purpose blitting loop.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline philfrei
« Reply #26 - Posted 2011-10-27 09:57:35 »

Quote
what would you suggest I do?

Do as much calculation as possible outside of the drawing!
Hence the value of loom_Weaver's point: "I hope you aren't scaling every frame i.e. every paint..."

For another example: how often (in terms of frames) does the -world.offsetX or ..Y change? Is it really every frame? Or can you calculate (-world.offsetX * 0.35) and store it when the offset changes, and use the stored value in your drawing?

Or this: does "-world.offsetY + world.worldHeight - (Assets.ground.getHeight()*2)" need to be calculated in its entirety every time? Or can you precalculate some of it?

Hope this helps. I know I am continually finding ways to move code out of the innermost loops.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline ~Spaceaholic

Senior Member


Medals: 3
Projects: 1



« Reply #27 - Posted 2011-10-27 14:38:26 »

Thank you again for all of you who have taken the time to help...

This thread has spawned a lot of talk about premature optimization, even after my last post which is clearly an area that is in diar need of optimization... was I a little premature to try and optimize my game loop, and updating methods, maybe, but its all part of the learning process... did it eventually lead me to a problem area within my code, YES, and its a problem area that is taking up between 35-50% of my game loop time, seams significant to me, especially considering it is drawing only three elements...

Back to the issue... I am scaling every frame, the reason is that I have an extremely limited space in memory for which to store my images(24 megs), so I must store them unscaled... the offset needs to be calculated every frame as the user is moving around within the world...

It seems my best attack plan as of yet would be to break my three images into tiles and only draw the portions necessary, I will still need to scale each tile, but overall it will be much less of a scaling procedure... 
Offline counterp

Senior Member


Medals: 11



« Reply #28 - Posted 2011-10-31 04:46:30 »

Webster's and CS defs aren't always the same are they?  If they were then all computer languages are functional languages.

http://en.wikipedia.org/wiki/Program_optimization

there's not really a CS definition for just 'premature' so, the term 'premature optimization' still equates to the same thing.
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #29 - Posted 2011-10-31 17:16:01 »

...an area that is in dire need of optimization...
Grin

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

pw (11 views)
2014-07-24 01:59:36

Riven (9 views)
2014-07-23 21:16:32

Riven (11 views)
2014-07-23 21:07:15

Riven (12 views)
2014-07-23 20:56:16

ctomni231 (42 views)
2014-07-18 06:55:21

Zero Volt (38 views)
2014-07-17 23:47:54

danieldean (32 views)
2014-07-17 23:41:23

MustardPeter (34 views)
2014-07-16 23:30:00

Cero (49 views)
2014-07-16 00:42:17

Riven (50 views)
2014-07-14 18:02:53
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!