0

I have a String which is of the form: 2013-10-20 15:18:39.954. I am trying to figure out the best way to store this data so that it would use the least possible memory. Currently I am storing it as a Date object in Java. From this link I found out that the object uses about 32 bytes of memory. Is there some way to use less memory to store this data? I am trying to use as low memory as possible, so even 1 byte lesser would be fine.

I was thinking that I could use a String but this link says Strings also use a lot of memory. Any help would be appreciated!

Community
  • 1
  • 1
RagHaven
  • 4,156
  • 21
  • 72
  • 113

2 Answers2

3

You can convert the Date to a long with the getTime() method (milliseconds since epoch) and back, and a long is 8 bytes.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thanks for the suggestion! Would happen to know what the complexity of each of those would be? – RagHaven Oct 21 '13 at 19:39
  • 1
    I would be really surprised if the complexity of these methods wasn't O(1). The performance shouldn't depend on the value here at all. – rgettman Oct 21 '13 at 19:43
1

A java.util.Date is just a long under the hood. You could represent the same information with a long and build Dates as necessary.

Just beware that storing information this way, either java.util.Date or long, is not fully portable across platforms if you convert it back to human readable representation.

The number of milliseconds since epoch that, for example, translates to 'Midnight June 18th, 2019' can change if a platform upgrade introduces new leap seconds, or daylight savings rules change.

Affe
  • 47,174
  • 11
  • 83
  • 83