Search code examples
dartnumbers

Does "num" use more resources than "int" in dart language?


I need to know if I always use "num" instead of "int" or "double" when I declare a variable is it bad for memory usage in Dart?

Is there any difference in terms of effective memory usage for these declarations in Dart?

num year = 1988;
num len = 181.45;

int year = 1988;
double len = 181.45;

Thanks in advance


Solution

  • Maybe!

    If the compiler can determine that the value is always an int anyway, it probably doesn't matter that you typed it as num. If it cannot detect that, then it may not apply optimizations special to int or double (like unboxed values internally in a function).

    The more important question is what you're trying to achieve by using num instead of int or double? Will the people maintaining your code be happy, when they don't actually know if it's an int or double?

    You can't use a num as an array index, that has to be an int, so generally you should use int for things that actually are ints.

    It's more questionable whether you should always used double instead of num for things that are (probably, almost) always doubles. There are very few places where a double is required, but they do exist.

    So, in general, using num prevents you from using the value in a place which requires an int or double (without calling .toInt() or .toDouble() first). That's the best reason to use the more precise type.

    Performance should only matter if you've identified the code as a performance hot-spot.