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....

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.

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?

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.

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?

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".

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.

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.

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...)

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.

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!

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

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.

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 worldthe world is 800x1600pxthe 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

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....

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)

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.

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.

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...

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