[H-GEN] Which is better?

Russell Stuart russell at stuart.id.au
Tue Apr 27 01:41:56 EDT 2004


On Tue, 2004-04-27 at 14:20, Harry Phillips wrote:
> First part:
> The difference is so small that there is no difference.
> 
> Second part:
> The compiler is very clever, just use it, if the code gets slow then 
> worry about it.

You learn quickly!  On machines that run Java, this the correct attitude
to have.  In Java and similar languages the greatest overhead comes from
their memory management.  Whereas C/C++ place most things tend to be
placed on the stack or made static, in Java everything and its dog
requires a call to the memory allocator.  This completely overshadows
the sorts of optimisations you were trying to implement.  If you want a
"rule to code" by to make java run quickly use this one: keep the number
of objects you create and destroy to a minimum.

This is often done in non-obvious ways.  For example, one serious design
error Java's creates now acknowledge is allowing a java.awt.Dimension to
be modified.  The reason is that a java.awt.Dimension is returned by
java.awt.Component.size(), among others.  Not unsurprisingly, size() is
a very common method to call.  However because the object returned can
be modified, the size() method has to create a new Dimension object for
each call.   Had the Dimension object been immutable, size() could of
returned the same object each time. It was decided this was causing a
serious speed issue, and as a result the getX() and getY() methods were
provided in java 1.2.

In hindsight, it is seems java would have suffered a great deal had
java.lang.String been mutable - for the same reasons.  As I recall, it
was made immutable to solve some fairly inscrutable security problem. 
So it was in one way a lucky fluke that java has immutable strings.

On the other hand, the advice given is just plain wrong when applied to
a different environment - eg when writing on a 4 bit micro in C.  In
that case the complier is invariably poor, and CPU cycles scarce.  The
code aj was a good example of what an experienced embedded programmer
would write out of habit.  He would write it because he has spent some
time looking at the assembler produced by the compiler, and can almost
visualise the machine instructions the compiler will produce as he types
in his code.  You may have also noticed that it was almost a readable as
your original unoptimised example.






More information about the General mailing list