patterncsharpMinor
Improving the code to turn a string into an array of numbers?
Viewed 0 times
turnthearrayintonumberscodestringimproving
Problem
I have a string of numbers, like "31654918562314", and I want to convert it into an array of integers. The code I've written is:
What improvements can I apply on this code? Is it the best ultimate code I can get to?
Note: I'm using C#. However, I also should implement this code in JavaScript.
string source = "31654918562314";
int[] numbers = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
numbers[i] = Convert.ToInt32(source.Substring(i, 1));
}What improvements can I apply on this code? Is it the best ultimate code I can get to?
Note: I'm using C#. However, I also should implement this code in JavaScript.
Solution
The most efficient code would be to use a plain loop and get the numerical value from the character code:
In Javascript you would use the
A performance test shows that using
string source = "31654918562314";
int[] numbers = new int[source.Length];
for (int i = 0; i < source.Length; i++) {
numbers[i] = source[i] - '0';
}In Javascript you would use the
charCodeAt method to do the same:var source = '31654918562314';
var numbers = new Array(source.length);
for (var i = 0; i < source.length; i++) {
numbers[i] = source.charCodeAt(i) - 48;
}A performance test shows that using
charCodeAt in a loop is 10-30 times faster than using a regular expression and parseInt: http://jsperf.com/string-to-array-of-numbersCode Snippets
string source = "31654918562314";
int[] numbers = new int[source.Length];
for (int i = 0; i < source.Length; i++) {
numbers[i] = source[i] - '0';
}var source = '31654918562314';
var numbers = new Array(source.length);
for (var i = 0; i < source.length; i++) {
numbers[i] = source.charCodeAt(i) - 48;
}Context
StackExchange Code Review Q#5383, answer score: 5
Revisions (0)
No revisions yet.