0

I brushed on this in another question I just asked, but I thought I'd ask it more explicitly. I'm working on a simple java game I'd like to run on android, using class instances to represent individual game units on the map. Each class contains about a dozen fields, which are mostly just simple strings or floats. I'm planning to store instances in a linked list.

How expensive would several hundred of these instances be in memory, roughly? When I originally sketched out the code structure, I was trying to limit the amount of extra data stored to reduce memory usage, but I'm now thinking that this was premature optimization. Is it really worth trying to optimize something so simple, or should I not worry about 300-ish simple class instances?

CMB
  • 133
  • 4
  • "How expensive would several hundred of these instances be in memory, roughly?" It entirely depends upon what those instances are instances of. – Andy Turner Sep 18 '18 at 07:49
  • @Andy Turner the class has about a dozen fields containing simple data types. – CMB Sep 18 '18 at 07:51
  • Several hundreds times a dozen times 4 bytes per float is `n * 100 * 12 * 4 B` , i.e., `n * 5 kB`. Android allows some 20 MB per process, so don't worry. Strings are more expensive, but when you share the same string in multiple instances, it only counts once (plus 4 bytes per instance for the reference to the string). – maaartinus Sep 18 '18 at 08:34
  • @maaartinus so basically they're cheap as dirt? – CMB Sep 19 '18 at 04:09
  • @CMB Sort of. I didn't mention the object header (IIRC 8 bytes on Android), but this is cheap. And you store them somewhere, which means 4 bytes for the reference in an `ArrayList` and maybe 20 bytes per element in a `LinkedList`. That's not bad, but `LinkedList` is nearly always wrong. – maaartinus Sep 19 '18 at 09:30
  • @maaartinus what do you mean LinkedList is nearly always wrong? In what way? – CMB Sep 19 '18 at 22:38
  • @CMB `LinkedList` is [nearly always slower](https://stackoverflow.com/q/322715/581205) and it needs 20 (or maybe more) bytes per element instead of 4. – maaartinus Sep 20 '18 at 16:49
  • @maaartinus I see. Thanks for the information. That's a big help. – CMB Sep 20 '18 at 17:26

0 Answers0