Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

36
LINES

< > BotCompany Repo | #1011517 - unsafe_sizeOf

JavaX fragment (include)

static Map<Class, Int> unsafe_sizeOf_cache = weakHashMap();

static int unsafe_sizeOf(O o) {
  Class c = _getClass(o);
  if (o instanceof O[])
    ret unsafe_sizeOf_uncached(o, c); // can't cache
  Int l = unsafe_sizeOf_cache.get(c);
  if (l == null)
    unsafe_sizeOf_cache.put(c, l = unsafe_sizeOf_uncached(o, c));
  ret l;
}
  
static int unsafe_sizeOf_uncached(O o, Class src) {
  int WORD = javaDataModelWordSize();
  int MIN_SIZE = 16;

  new L<Field> instanceFields;
  while (src != null && src != O.class && empty(instanceFields)) {
    for (Field f : src.getDeclaredFields())
      if ((f.getModifiers() & Modifier.STATIC) == 0)
        instanceFields.add(f);
    src = src.getSuperclass();
  }
  
  long maxOffset = MIN_SIZE;
  
  if (o instanceof O[]) {
    int n = l((O[]) o);
    maxOffset = lowestValue(unsafe_allFieldOffsets(Pair)) + 4 + java_pointerSize()*(n-1);
  } else // TODO: add primitive arrays
    for (Field f : instanceFields) {
      long offset = cast call(theUnsafe_gen(), 'objectFieldOffset, f);
      if (offset > maxOffset) maxOffset = offset; 
    }
  ret (((int) maxOffset/WORD) + 1)*WORD; 
}

Author comment

from https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java (modified)

download  show line numbers  debug dex   

Travelled to 10 computer(s): aoiabmzegqzx, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, tslmcundralx, tvejysmllsmz

No comments. add comment

Snippet ID: #1011517
Snippet name: unsafe_sizeOf
Eternal ID of this version: #1011517/18
Text MD5: 6b4a6fc38beea4d1c2a1417855c0f50c
Author: stefan
Category: javax / unsafe
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-04-17 07:16:58
Source code size: 1161 bytes / 36 lines
Pitched / IR pitched: No / No
Views / Downloads: 534 / 594
Version history: 17 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1011517 & http://1011517.tinybrain.de