using variables vs straight up numbahs...

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…

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?

thanks…

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.

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.

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

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

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

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.

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

premature != early :wink:

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.

how is that an oxymoron?

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

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.

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 :slight_smile:

Long story short: magic numbers bad, symbolic constants good :slight_smile:

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.