-1

In C#, if I initialize a byte and later cast it to an int have more of an overhead than just initializing an int from the start? For example, does this:

    int foo = 2;
    int bar = 3;
    int foobar = foo + bar;

Have more of a performance overhead than this?

    byte foo = 2;
    int bar = 3;
    int foobar = (int) foo + bar;
Pacific Bird
  • 286
  • 1
  • 3
  • 13
  • @Aominè but does casting it cause more memory to be allocated? – Pacific Bird Jun 08 '17 at 20:02
  • may be answered here. https://stackoverflow.com/questions/1923882/how-expensive-is-casting-an-object – Tianyun Ling Jun 08 '17 at 20:03
  • 5
    You've written the code both ways. Now run it, and *see which way works better*. If you can't tell the difference, then what does it matter which way you wrote it? A performance difference that you cannot measure or perceive is not a difference that matters. – Eric Lippert Jun 08 '17 at 20:03
  • 1
    More generally: make types reflect the semantics of the data. The reason to use int instead of byte is because *the quantity is logically an integer, not logically a byte*, not which is more performant. – Eric Lippert Jun 08 '17 at 20:05
  • @Sharp_ If you know that there's no relevant difference, then why waste people's time asking a question that you already knew the answer to. – Servy Jun 08 '17 at 20:08
  • Look at this https://stackoverflow.com/questions/2410181/how-to-see-jit-compilated-code-in-net-vm-clr and answer that kind of questions by yourself – Sir Rufo Jun 08 '17 at 20:11

1 Answers1

1

seems like you think its a good idea to save 3 bytes by making foo a byte. Its not, it wont make any speed or space difference and it will simply confuse readers of the code (including you), and add subtle bugs when you change the code later.

If you were storing lots of numbers and you know the were all 1 byte then yes this would save space an you should do it. But not in the trivial case you show

pm100
  • 48,078
  • 23
  • 82
  • 145