Is string interning really useful?

前端 未结 7 1988
北恋
北恋 2020-12-30 00:26

I was having a conversation about strings and various languages a while back, and the topic of string interning came up. Apparently Java and the .NET framework do this auto

相关标签:
7条回答
  • 2020-12-30 01:03

    The a.equals(b) is very fast for random strings. Its is only slow for Strings which are long and the same (or almost the same)

    Random rand = new Random(1);
    String[] list = new String[2000];
    for(int i=0;i<list.length;i++)
        list[i] = "1234567"+Long.toString(rand.nextInt(36*37), 36); // semi random
    int count = 0;
    long start = System.nanoTime();
    for(int i=0;i<list.length;i++)
        for(int j=0;j<list.length;j++)
            if (list[i].equals(list[j]))
                count++;
    long time = System.nanoTime() - start;
    System.out.printf("The average time for equals() was %,d ns.%n", time/list.length/list.length);
    

    on a 2.3 GHz laptop prints

    The average time for equals() was 19 ns.
    

    If you intern() the first value and have to intern() one value to do the comparison

           if (list[i] == list[j].intern())
    

    prints

    The average time for equals() was 258 ns.
    

    This is a common case as you often have one value you know is interned and a second which is input and is not intern'ed.

    if you only use intern'ed Strings and == it, and don't count the cost, prints

    The average time for equals() was 4 ns.
    

    Which is many times faster if you are doing millions of comparison. However for a small number of comparisons, you are saving 8 ns but could be costing 250 ns more.

    It may just be simpler to avoid intern() and use equals().

    0 讨论(0)
提交回复
热议问题