6
$\begingroup$

Is there a way to convert a list of string to numbers faster than ToExpression?

str = ToString /@ RandomReal[100, 1000];
ToExpression@str; // AbsoluteTiming // First
(* 0.007714 *)

Related: How to convert string to integer list?

Edit Thanks to J.M. who pointed to this answer:

  Internal`StringToDouble/@str; // AbsoluteTiming // First
 (* 0.000834 *)
$\endgroup$
  • 2
    $\begingroup$ Have you seen this? $\endgroup$ – J. M. will be back soon Mar 7 '18 at 21:50
  • 1
    $\begingroup$ @J.M. Wow, no I had not! Probably hard to beat... $\endgroup$ – anderstood Mar 7 '18 at 21:55
5
$\begingroup$

I'd just like to point out the J.M.'s answer is also best if you have ints, since Floor is fast and listable as a cast from Real:

intStrings = RandomInteger[10000, 100000] // Map[ToString];

Floor[Internal`StringToDouble /@ intStrings] // RepeatedTiming // First

0.048

ToExpression@intStrings // RepeatedTiming // First

0.413
$\endgroup$
  • $\begingroup$ Maybe you can incorporate J.M.'s answer too (as community if you're not comfortable) so that I can accept it. $\endgroup$ – anderstood Jun 11 '18 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.