7
$\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
  • 3
    $\begingroup$ Have you seen this? $\endgroup$ Mar 7, 2018 at 21:50
  • 1
    $\begingroup$ @J.M. Wow, no I had not! Probably hard to beat... $\endgroup$
    – anderstood
    Mar 7, 2018 at 21:55

1 Answer 1

6
$\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$
1
  • $\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, 2018 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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