Quickest method to convert Vector of Strings to 3 Vectors of Floats

Hello,

I have a vector of String like

a = ["0.309042 46.586349 111.4", "0.309042 46.586349 111.1", "0.309042 46.586349 111.3"]

and want to get 3 vectors of coordinates (longitude, latitude, altitude) (Float64)

I did

a = split.(a)
longitude = [parse(Float64, c[1]) for c in a]
latitude = [parse(Float64, c[2]) for c in a]
altitude = [parse(Float64, c[3]) for c in a]

I wonder if there isn’t a quicker method

function timethis()
    a = ["0.309042 46.586349 111.4", "0.309042 46.586349 111.1", "0.309042 46.586349 111.3"]
    a = split.(a)
    longitude = [parse(Float64, c[1]) for c in a]
    latitude = [parse(Float64, c[2]) for c in a]
    altitude = [parse(Float64, c[3]) for c in a]
    return longitude, latitude, altitude
end

julia> @time timethis()
  0.407742 seconds (237.58 k allocations: 11.579 MiB, 39.14% gc time)
([0.309042, 0.309042, 0.309042], [46.586349, 46.586349, 46.586349], [111.4, 111.1, 111.3])

Kind regards

I am not sure if there is a faster approach, but there are some issues with your timing.
It seems that you are mainly timing compile time:

julia> function timethis()
           a = ["0.309042 46.586349 111.4", "0.309042 46.586349 111.1", "0.309042 46.586349 111.3"]
           a = split.(a)
           longitude = [parse(Float64, c[1]) for c in a]
           latitude = [parse(Float64, c[2]) for c in a]
           altitude = [parse(Float64, c[3]) for c in a]
           return longitude, latitude, altitude
       end
timethis (generic function with 1 method)

julia> @time timethis()
  0.118533 seconds (436.11 k allocations: 21.948 MiB, 3.99% gc time)
([0.309042, 0.309042, 0.309042], [46.586349, 46.586349, 46.586349], [111.4, 111.1, 111.3])

julia> @time timethis()
  0.000018 seconds (37 allocations: 1.719 KiB)
([0.309042, 0.309042, 0.309042], [46.586349, 46.586349, 46.586349], [111.4, 111.1, 111.3])

To benchmark your function try this:

julia> using BenchmarkTools

julia> a = ["0.309042 46.586349 111.4", "0.309042 46.586349 111.1", "0.309042 46.586349 111.3"]

julia> @benchmark timethis($a)
BenchmarkTools.Trial:
  memory estimate:  1.45 KiB
  allocs estimate:  32
  --------------
  minimum time:     6.980 μs (0.00% GC)
  median time:      7.180 μs (0.00% GC)
  mean time:        9.269 μs (12.97% GC)
  maximum time:     9.537 ms (99.88% GC)
  --------------
  samples:          10000
  evals/sample:     5
2 Likes

Here are some more examples on how to do it in other ways:

(i case you don’t follow the discourse)