Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (480)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (546)
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  
  Casting Objects  (Read 5284 times)
0 Members and 1 Guest are viewing this topic.
kul_th_las
Guest
« Posted 2003-08-11 22:43:07 »

Are Object casts (to a subclass) processor expensive?
Offline Mark Thornton

Senior Member





« Reply #1 - Posted 2003-08-12 07:45:39 »

No. On my machine (P4 3.06GHz) a cast from Object to Integer appears to take about one clock cycle. It is difficult to measure this reliably, which is really more evidence that you should not worry about it.
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #2 - Posted 2003-08-12 10:12:54 »

Quote
a cast from Object to Integer appears to take about one clock cycle.


One clock cycle of what clock is that? Certainly not the CPU's clock I suppose...

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

Senior Member





« Reply #3 - Posted 2003-08-12 10:42:17 »

Yes the CPU clock cycle. In other words the casts appear to be costing of the order of 0.3ns.
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #4 - Posted 2003-08-12 10:58:47 »

How can that be and how did you measure that?
The last time I checked, no 1 CPU instruction takes as little as 1 clock cycle so how can a java type cast cost so little?. Or maybe something has changed in this (I haven't done any asm in years)?

(BTW. I know it's a bit off topic nitpicking as you're right this casting is not costly at all Smiley)

Offline swpalmer

JGO Coder




Where's the Kaboom?


« Reply #5 - Posted 2003-08-12 11:23:59 »

I think on modern processors with fancy pipeline architectures the THROUGHPUT can be one instruction per clock or more.  The actual instruction takes several cycles.. but because of the pipeline there are several instruction in progress at any one time and (at least) one instruction FINISHES on each clock cycle.  This of course is the optimal case, many things can happen to stall the pipeline.

That said, I find it hard to believe that a cast can happen so quickly.  Surely it takes several instruction to do the cast, given that a check needs to be made on the validity of the cast re:throw an exception or not.  Plus possibly some pointer/table adjustment to gain access to new methods that are available after the cast.  One instruction just seems far too cheap.  Although I recall reading that the cost of a cast has gone down from what it used to be with older VMs.

Offline abies

Senior Member





« Reply #6 - Posted 2003-08-12 12:09:38 »

Cast can be actually free if you already know that object extends given class. If it is not a case, what is left is just a check if superclass of object at given depth is equal to compile time constant - something like

cmp [eax+depth_offset], constant
jne exception

With branch being default to non-taken, eax pointing to object class. Simple cmp and non-taken-jne can be resolved in single clock as far as I remember.
You may need a one instruction more to get pointer to object class, but it will be free if you use some method of object afterwards, as you will have to resolve it anyway.

1 clock seems reasonable estimation, with maybe one or two more in more complicated cases. Not much to worry about.

Of course, if we are talking about interface casts, situation looks quite different...

Artur Biesiadowski
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #7 - Posted 2003-08-12 12:25:45 »

Ah, of course, the pipe line.
Never had to deal with that on a 68k Grin
I read a few articles the other day about how to prevent stalling the pipeline, but the code that that resulted in was so utterly unreadable and it all complicated things so much that I didn't bother to get into asm on recent CPU's again  Tongue

Offline Mark Thornton

Senior Member





« Reply #8 - Posted 2003-08-12 14:30:24 »

It doesn't even matter whether the branch is taken or not these days provided the processor correctly predicted which route would be followed. The branch prediction on casting should be good if the objects being cast are all the same type.
Offline swpalmer

JGO Coder




Where's the Kaboom?


« Reply #9 - Posted 2003-08-12 16:44:47 »

Quote
...what is left is just a check if superclass of object at given depth is equal to compile time constant - something like

cmp [eax+depth_offset], constant
jne exception

Cool.  Now that I think about it, I guess it really can be that simple!  You can't get much cheaper than that.. except for the 'free' case where the cast is known to be safe of course.
Hmm.. Is depth_offset a constant though? Would it not depend on the actual type of the object?  I guess it will always be fixed distance from the root Object.. but the size of such a lookup table would depend on the actual object type wouldn't it?

class A extends Object {}
class B extends A {}
class C extends B {}

Checking if A is a valid B or C would look into the table, but if A is really a B and we try to cast it to a C do we go one step too far into the table?


Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
kul_th_las
Guest
« Reply #10 - Posted 2003-08-12 21:33:50 »

So, it's essentially super-cheap.

I was asking because I'll be doing quite of lot of it at times in some portions of my main game loop, and I was wondering whether or not a not-cast solution would yeild performace benefits worth chasing. Probably not, in this case.

Of course, my game code is still in the early stages, so I haven't got the the optimization step yet, but I do appreciate the comments for future reference.
Offline kevglass

JGO Kernel


Medals: 152
Projects: 23
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #11 - Posted 2003-08-13 04:30:07 »

I don't think there is much you can do about casting in your main loop if you want to use any sort of Container, well apart from reverting to arrays everywhere.

This should be sorted as of Generic in Java 1.5 tho..

Kev

kul_th_las
Guest
« Reply #12 - Posted 2003-08-13 05:14:40 »

This is true (about 1.5). However, I'm writing a code library at the moment for use in my game (the part that will be called many times in the main loops of my projects), and I'd like this code to be around for quite a while.

So, I don't think I'll be worrying about the casts. But then again, do I really care that about making the generics change to my library when 1.5 comes out? I don't think so. Doing so would make it incompatible with any previous JDK.

Then again, what's the point? Why should I take the time to make tedious changes to the library if the performance difference is, in this case, negligible?
Offline abies

Senior Member





« Reply #13 - Posted 2003-08-13 05:16:51 »

Quote

class A extends Object {}
class B extends A {}
class C extends B {}

Checking if A is a valid B or C would look into the table, but if A is really a B and we try to cast it to a C do we go one step too far into the table?


You just need to make such lookup table constant in size, even for classes which are not deep in inheritance tree. This means umpteen wasted bytes per class, but IMHO it is acceptable tradeoff for speedup. Few years ago I have done some profiling checks
http://nwn-j3d.sourceforge.net/misc/stattable.html
Depth 5 seems to be very good choice - as depth is known at jit compile time, for depth 6+ jvm can just use normal, iterate-through-superclasses check.

Artur Biesiadowski
Offline kevglass

JGO Kernel


Medals: 152
Projects: 23
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #14 - Posted 2003-08-13 05:18:36 »

Agreed, it will be a lot of hassle..

But, if Generics are implemented like Templates are in C++ it will only mean that you can't compile your source on older JDKs, won't cause a problem running it, since the Generic will have just generated an appropriate class... although, I don't know the details of how generics will be implemented.

As to why to move to generics, well unless you're writing type safe wrappers for all you containers (which tbh, I try to) you'll be exposing an Object as the contained element in quite a few places. This is quite bad from a code robustness point of few. Moving to Generics in this case will most likely make the code far more resiliant to accidental coding problems..

Kev

Offline Matlu

Junior Member




Hasta La Victoria Siempre!


« Reply #15 - Posted 2005-07-26 10:08:04 »

I also wondered how expensive typecast is. Following code displays:
~ 200 ms WITHOUT typecast
~ 1000 ms WITH typecast

My interpretation is:   typecast takes four times longer to execute, THAN method invocation + integer divide  (at least in this case). I'm not sure if it's correct interpretation though

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
public class Test {

   private static final int COUNT         = 50000000;
   private static Test object1 = new Test();
   private static Object object2 = new Test();
   
   public static void main(String[] args) {
     
      long startTime = System.currentTimeMillis();
      test();      
      long diff = System.currentTimeMillis() - startTime;
      System.out.println("Without typecast: " + diff);

      startTime = System.currentTimeMillis();
      test2();      
      diff = System.currentTimeMillis() - startTime;
      System.out.println("With typecast: " + diff);
   }

   private static void test()
   {
      for (int i=0; i<COUNT; i++)
      {
         object1.testMethod();
         object1.testMethod();
         object1.testMethod();
         object1.testMethod();
         object1.testMethod();
      }
   }

   private static void test2()
   {
      for (int i=0; i<COUNT; i++)
      {
         ((Test) object2).testMethod();
         ((Test) object2).testMethod();
         ((Test) object2).testMethod();
         ((Test) object2).testMethod();
         ((Test) object2).testMethod();
      }
   }

   public void testMethod()
   {      
      int i = 10 / 3;
   }
}

Multiplayer Online Games
http://www.duelboard.com
Offline kevglass

JGO Kernel


Medals: 152
Projects: 23
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #16 - Posted 2005-07-26 11:05:38 »

The point being that should only use type casts where you *have* to? Not that surpising.

Kev

Offline princec

JGO Kernel


Medals: 361
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #17 - Posted 2005-07-26 12:37:31 »

Doesn't the server VM do some clever stuff to optimise casts away completely?

Cas Smiley

Offline Matlu

Junior Member




Hasta La Victoria Siempre!


« Reply #18 - Posted 2005-07-26 12:44:47 »

The point being that should only use type casts where you *have* to? Not that surpising.

Kev
Well, you *never* have to. You can always make some crazy not-very-OO construction (or at least replace collections with arrays). The point was to find out whether it's worth it.

Multiplayer Online Games
http://www.duelboard.com
Offline kevglass

JGO Kernel


Medals: 152
Projects: 23
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #19 - Posted 2005-07-26 13:58:35 »

And my point was that whether you have to or not isn't just dependent on performance.

Kev

Offline Jeff

JGO Coder




Got any cats?


« Reply #20 - Posted 2005-07-29 04:20:52 »

So I thin kthis has been answred but
(1) No.  The cast itself is free HOWEVER in some (but not all) cases it implies a run-time type check.  This is very very cheap. but not 100% free.


Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
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.

atombrot (21 views)
2014-08-19 09:29:53

Tekkerue (21 views)
2014-08-16 06:45:27

Tekkerue (21 views)
2014-08-16 06:22:17

Tekkerue (12 views)
2014-08-16 06:20:21

Tekkerue (19 views)
2014-08-16 06:12:11

Rayexar (56 views)
2014-08-11 02:49:23

BurntPizza (37 views)
2014-08-09 21:09:32

BurntPizza (29 views)
2014-08-08 02:01:56

Norakomi (35 views)
2014-08-06 19:49:38

BurntPizza (65 views)
2014-08-03 02:57:17
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
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!