的String []内存使用 [英] String[] Memory Usage

查看:99
本文介绍了的String []内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明一个String数组:

I am declaring a String array as:

String[] items1 = new String[5];
String[] items2 = new String[20];

多大影响这两个阵列将会对内存和性能如果两个只包含2个元素。

How much effect both of these arrays will produce on memory and performance if both contain only 2 elements.

推荐答案

您也可以自己进行测试。

You can test this yourself.

public static void main(String... args) {
    long free1 = free();
    String[] two = new String[2];
    long free2 = free();
    String[] twenty = new String[20];
    long free3 = free();
    if (free3 == free1) System.err.println("You need to use -XX:-UseTLAB");
    System.out.println("String[2] took " + (free1 - free2) + " bytes and String[20] took " + (free2 - free3) + " bytes.");
}

private static long free() {
    return Runtime.getRuntime().freeMemory();
}

打印

String[2] took 24 bytes and String[20] took 96 bytes.

所以你可能会浪费了72个字节的内存。如果你的内存成本为每GB $ 10你可能会浪费内存0.000072美分。然而,你的时间第二个可能价值2美分。在这种情况下,硬是不值得花一毫秒的在这种情况下担心。即所花费的时间写20,而不是2的价值远,远不止这些。

So you could be wasting 72 bytes of memory. If your memory cost $10 per GB, you could be wasting 0.000072 cents of memory. However, a second of your time could be worth 2 cents. In this case it is literally not worth spending a milli-second worrying about it in this case. i.e. The time it takes to write 20 instead of 2 is worth far, far more.

这篇关于的String []内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆