views:

77

answers:

2

How do I get the amount of physical memory, consumed by the DataSource (specifically — ByteArrayDataSource)? I use javax.mail.util.ByteArrayDataSource (byte[] bytes, String type) constructor, where I get bytes like this:

String str = "test";
byte[] bytes = str.getBytes();

Would that be str.length() in bytes? Any other ideas?

+1  A: 

str.length() will give the number of characters

bytes.length will give the actual number of bytes.

Depending on your active character set this may or may not be the same. Some characters are encoded as multiple bytes.

example :

public static void main(String[] args) {
    String s1 = "test";
    byte[] b1 = s1.getBytes();
    System.out.println(s1.length());
    System.out.println(b1.length);

    String s2 = "\u0177";
    byte[] b2 = s1.getBytes();
    System.out.println(s2.length());
    System.out.println(b2.length);

}

returns

4 4 1 4

Peter Tillemans
Java Strings always consume 2 bytes per character (well, plus a little internal overhead) since Java char are 2 bytes and the in-memory encoding is effectively always UCS-2.
Sean Owen
+1  A: 

It's not clear what you're asking.

The number of bytes consumed by a byte[] is just its length: bytes.length The number of bytes consumed, in memory, by a Java String, is 2 bytes per character, since in memory it is encoded as UCS-2: 2*str.length() The number of bytes consumed by a String, when serialized to a byte[], depends on the character encoding you select. You would have to serialize it and check.

But what are you really trying to do?

Sean Owen