Fastest way to separate the digits of an int into an array in .NET?

后端 未结 11 811
天涯浪人
天涯浪人 2021-01-31 20:07

I want to separate the digits of an integer, say 12345, into an array of bytes {1,2,3,4,5}, but I want the most performance effective way to do that, because my program does tha

11条回答
  •  春和景丽
    2021-01-31 20:52

    The allocation of a new int[] every time takes up a significant amount of the time according to my testing. If you know these values will be used once and thrown away before the next call, you could instead reuse a static array for a significant speed improvement:

        private static readonly int[] _buffer = new int[10];
        public static int[] ConvertToArrayOfDigits(int value)
        {
            for (int index = 9; index >= 0; index--)
            {
                _buffer[index] = value % 10;
                value = value / 10;
            }
            return _buffer;
        }
    

    to keep the code small, I am returning trailing zero's for smaller numbers, but this could easily be changed by using 9 different static arrays instead (or an array of arrays).

    Alternatively, 2 seperate ConvertToArrayOfDigits methods could be provided, one taking a precreated int array as an extra parameter, and one without that which creates the resulting buffer prior to calling the first method.

        public static void ConvertToArrayOfDigits(int value, int[] digits) { ... }
        public static int[] ConvertToArrayOfDigits(int value)
        {
            int size = DetermineDigitCount(value);
            int[] digits = new int[size];
            ConvertToArrayOfDigits(value, digits);
            return digits;
        }
    

    This way, it would be up to the caller to potentially create a static reusable buffer if their usecase allows for it.

提交回复
热议问题