直接访问在某些情况下,合理的String的支持数组? [英] Is directly accessing the backing array of a String justified in some cases?

查看:123
本文介绍了直接访问在某些情况下,合理的String的支持数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在优化的文字处理软件,在下面的类使用了大量的:

I'm working on optimizing text processing software, in which the following class is used a lot:

class Sentence {

  private final char[] textArray;
  private final String textString; 

  public Sentence(String text) {
     this.textArray = text.toCharArray();
     this.textString = text;
  }

  public String getString() {
     return textString;
  }

  public char[] getArray() {
     return textArray;
  } 
}

正如你所看到的,有一些冗余:在textString的支持数组总是等于textArray,但都存储。

As you can see, there is some redundancy: the backing array of the textString is always equal to the textArray, yet both are stored.

我希望通过摆脱textArray领域,以减少这一类的内存占用。

I'm hoping to reduce the memory footprint of this class, by getting rid of the textArray field.

有一个问题:这个类是广泛使用througout了codeBase的,因此,我无法摆脱的getArray()方法。我的解决办法是摆脱textArray领域,并让
而是通过反射的getArray()方法返回textSting的支持数组。

There is one problem : this class is used widely througout out codebase, thus I cannot get rid of getArray() method. My solution is to get rid of the textArray field, and let the getArray() method return the textSting's backing array instead via reflection.

其结果会是这样的:

class Sentence {

  private final String textString; 

  public Sentence(String text) {
       this.textString = text;
  }

  public String getString() {
     return textString;
  }

  public char[] getArray() {
     return getBackingArrayUsingReflection(textString);
  } 
}

这似乎是一个可行的解决方案,但我怀疑一个String的底层实现数组是私有的一个原因。什么是这种方法潜在的问题?

It seems like a viable solution, but I suspect a String's backing array is private for a reason. What are potential problems with this approach?

推荐答案

有一件事情会发生是你自己承诺的一个具体实施的JDK。例如,Java 7更新6已全新改版其使用的的char [] 。这就是为什么这种做法应该被容忍只有当您的code是非常短暂的,基本上都是被扔掉的code。

One thing that will happen is that you are committing yourself to one specific implementation of the JDK. For example, Java 7 Update 6 has totally revamped its use of the char[]. This is why such an approach should be tolerated only if your code is very ephemeral, basically throw-away code.

如果你只读的char [] ,而你编码的OpenJDK Java 7中,更新6,你不会引入任何错误。

If you are only reading the char[], and you are coding for OpenJDK Java 7, Update 6, you won't introduce any bugs.

在另一方面,世界各地的Java程序员的95%可能会在code在字符串,反映大摇其难以置信的头内部,所以要小心:)

On the other hand, 95% of Java programmers around the world would probably shake their heads in disbelief at code that reflects upon String internals, so be careful :)

这篇关于直接访问在某些情况下,合理的String的支持数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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