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 that millions of times.
Any suggestions? Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How about:
Note that this won’t cope with negative numbers… do you need it to?
EDIT: Here’s a version which memoizes the results for under 10000, as suggested by Eric. If you can absolutely guarantee that you won’t change the contents of the returned array, you could remove the
Clonecall. It also has the handy property of reducing the number of checks to determine the length of “large” numbers – and small numbers will only go through that code once anyway 🙂Note that this doesn’t try to be thread-safe at the moment. You may need to add a memory barrier to make sure that the write to the memoized results isn’t visible until the writes within the individual result are visible. I’ve given up trying to reason about these things unless I absolutely have to. I’m sure you can make it lock-free with effort, but you should really get someone very smart to do so if you really need to.
EDIT: I’ve just realised that the “large” case can make use of the “small” case – split the large number into two small ones and use the memoised results. I’ll give that a go after dinner and write a benchmark…
EDIT: Okay, ready for a giant amount of code? I realised that for uniformly random numbers at least, you’ll get “big” numbers much more often than small ones – so you need to optimise for that. Of course, that might not be the case for real data, but anyway… it means I now do my size tests in the opposite order, hoping for big numbers first.
I’ve got a benchmark for the original code, the simple memoization, and then the extremely-unrolled code.
Results (in ms):
Code: