Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Julia将值字符串读取到数组的最快方法_String_Performance_Optimization_Type Conversion_Julia - Fatal编程技术网

String Julia将值字符串读取到数组的最快方法

String Julia将值字符串读取到数组的最快方法,string,performance,optimization,type-conversion,julia,String,Performance,Optimization,Type Conversion,Julia,我有一个多字符串的数组,其值实际上是各种类型的数组,例如: Julia> _string "[(-33.8800966, 151.2069034), (-33.8801202, 151.2071933), (-33.8803442, 151.2083656), (-33.8804469, 151.2088682), (-33.8788247, 151.2104533)]" Julia> typeof(_string) String Julia> _string2 "[1,

我有一个多字符串的数组,其值实际上是各种类型的数组,例如:

Julia> _string
"[(-33.8800966, 151.2069034), (-33.8801202, 151.2071933), (-33.8803442, 151.2083656), (-33.8804469, 151.2088682), (-33.8788247, 151.2104533)]"

Julia> typeof(_string)
String

Julia> _string2
"[1, 2, 3, 4]"

Julia> typeof(_string2)
String
我想快速地将它们转换成数组,我知道每个字符串的类型

i、 e.so

Julia> convert(Array{Tuple(Float64, Float64)}, _string)
(-33.8800966, 151.2069034), (-33.8801202, 151.2071933), (-33.8803442, 151.2083656), (-33.8804469, 151.2088682), (-33.8788247, 151.2104533)]

Julia> convert(Array{Int,1}, _string2)
[1, 2, 3, 4]
目前我使用的是
eval(Meta.parse(_string))
,重复数百万次时速度非常慢


快速将这些字符串读入数组的快速方法是什么?

这可能不是最好的答案,但加快速度的一种方法是利用您掌握的字符串结构的任何信息来解析字符串,例如,对于第二个示例:

julia> using BenchmarkTools

julia> @btime parse.(Int64, split(replace(replace($_string2, "[" => ""), "]" => ""), ","))
  995.583 ns (19 allocations: 944 bytes)
4-element Array{Int64,1}:
 1
 2
 3
 4
与之相比

julia> @btime eval(Meta.parse($_string2))
  135.553 μs (43 allocations: 2.67 KiB)
4-element Array{Int64,1}:
 1
 2
 3
 4
在我的机器上


当然,这是否可行取决于您是否能够以这种方式快速找到所有字符串的模式

请注意,您不需要两个
replace
调用。只需在一次调用中提供任意多个替换对。显然,我之前的评论是错误的:根据文档,它应该可以工作。是的,我认为您需要类似于
foldl(replace,[…pairs…],init=\u string)的东西
让它发挥作用,但我总是记不太清楚,而且我通常懒得找出有解决方案的对话线索:)你也可以使用
切碎(_string2;head=1,tail=1)
删除第一个和最后一个字符。这要快得多。谢谢大家,这很有帮助,我会用我专门用来让字符串更快读入的方法更新你的答案