Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is encapsulating Strings as byte[] in order to save memory overkill ? (Java)

Was recently reviewing some Java Swing code and saw this:

byte[] fooReference;

String getFoo() {
   returns new String(fooReference); 
}

void setFoo(String foo) {
  this.fooReference = foo.getBytes();
}

The above can be useful to save on your memory foot print or so I'm told.

Is this overkill is anyone else encapsulating their Strings in this way?

like image 573
JARC Avatar asked Jul 29 '10 22:07

JARC


1 Answers

That's a really, really bad idea. Don't use the platform default encoding. There's nothing to say that if you call setFoo and then getFoo that you'll get back the same data.

If you must do something like this, then use UTF-8 which can represent the whole of Unicode for certain... but I really wouldn't do it. It potentially saves some memory, but at the cost of performing conversions unnecessarily for most of the time - and being error-prone, in terms of failing to use an appropriate encoding.

I dare say there are some applications where this would be appropriate, but for 99.99% of them, it's a terrible idea.

like image 69
Jon Skeet Avatar answered Nov 03 '22 01:11

Jon Skeet