• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how can i know size of object in memory

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all

how can i know how much memory object is in memory

throw code or IDE ? or something

thanks
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34668
366
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Meir,
You can use a profiler and drill down to the object or write code. For code, write the object to a stream and see how many bytes it is.

With either approach, note that you might overcount the memory used. If another object shares objects owned by your app, they will be counted. Even though they may be shared by many objects.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12143
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
one of the things about java is that you don't NEED to know. Java has built in memory management, so you don't need to calculate the size to find an offset.

I guess my question to you would be "Why do you want to know? What do you hope to gain by knowing, or do with the info?"

if it's purely an academic exercise, OK, but if you have some pressing design need, there's probably a better way.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm with Fred on this one... given that this is the beginner's forum I would say that the first step would be to understand exactly how reference variables and objects interact, and to understand exactly when an object becomes eligible for garbage collection. From a memory management perspective, the single best thing you can do as a programmer is to understand how to make an object eligible for garbage collection.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've worked in other languages that had a sizeOf(object) feature and we thought we really needed it to tune designs. Years of working without it in Java shows that we really didn't need it for that purpose, though I'm still curious sometimes. The Java Specialists newsletter shows how to get a pretty good estimate. I've never actually tried it, because I can't really answer the questions Fred asked.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic