Does it really matter to distinct between short, int, long?

前端 未结 11 626
名媛妹妹
名媛妹妹 2021-01-17 09:46

In my C# app, I would like to know whether it is really important to use short for smaller numbers, int for bigger etc. Does the memory consumption really matter?

相关标签:
11条回答
  • 2021-01-17 10:25

    That all depends on how you are using them and how many you have. Even if you only have a few in memory at a time - this might drive the data type in your backing store.

    0 讨论(0)
  • 2021-01-17 10:27

    Unless you are packing large numbers of these together in some kind of structure, it will probably not affect the memory consumption at all. The best reason to use a particular integer type is compatibility with an API. Other than that, just make sure the type you pick has enough range to cover the values you need. Beyond that for simple local variables, it doesn't matter much.

    0 讨论(0)
  • 2021-01-17 10:32

    The context of the situation is very important here. You don't need to take a guess at whether it is important or not though, we are dealing with quantifiable things here. We know that we are saving 2 bytes by using a short instead of an int.

    What do you estimate the largest number of instances are going to be in memory at a given point in time? If there are a million then you are saving ~2Mb of Ram. Is that a large amount of ram? Again, it depends on the context, if the app is running on a desktop with 4Gb of ram you probably don't care too much about the 2Mb.

    If there will be hundreds of millions of instances in memory the savings are going to get pretty big, but if that is the case you may just not have enough ram to deal with it and you may have to store this structure on disk and work with parts of it at a time.

    0 讨论(0)
  • 2021-01-17 10:33

    For C# apps that aren't trying to mirror some sort of structure from a file, you're better off using ints or whatever your native format is. The only other time it might matter is if using arrays on the order of millions of entries. Even then, I'd still consider ints.

    0 讨论(0)
  • 2021-01-17 10:36

    The simple answer is that it's not really important.

    The more complex answer is that it depends.

    Obviously you need to choose a type that will hold your datastructure without overflowing, and even if you're only storing smaller numbers then choosing int is probably the most sensible thing to do.

    However, if your application loads a lot of data or runs on a device with limited memory then you might need to choose short for some values.

    0 讨论(0)
  • 2021-01-17 10:38

    The answer is: it depends. The question of whether memory matters is entirely up to you. If you are writing a small application that has minimal storage and memory requirements, then no. If you are google, storing billions and billions of records on thousands of servers, then every byte can cost some real money.

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