I tried to compare string concatenation using ropes and system's add, but seems the bench mark result is not right... Does anyone know how to use this module efficiently? (Also, I must admit that I never used rope algorithm, so I might doing wrong)


import times, ropes

proc strBench(sample: Rope|string) =
  var str = when sample is Rope: rope("") else: ""
  let startTime = getTime()
    let endTime = getTime()
    echo endTime.toSeconds() - startTime.toSeconds()
  for i in 0 .. 6_000_000:
    str.add sample

const sample = "something\n"

# nim c -r rope_test.nim
#   rope version -> 3 sec
#   normal version -> 1 sec

2017-10-08 09:43:11
Seems ok to me, ropes are slow, don't use them. 2017-10-09 15:37:51
They are for long strings, you'll get different result with several kilobytes text in your constant. Of coarse you then have to lower cycles to not get out of memory, or reset str from time to time. Yet probaly use cpuTime or epochTIme to get floats - times can get to 0 seconds.
2017-10-09 18:25:42

Is my understanding correct that both string and Rope have O(1) appends?

I think string has amortized O(1) due to growing buffer space, whereas Rope has straight-up O(1) runtime complexity.

But what might matter more here is the constant factor, and I think string ends up doing much fewer allocations than Rope, which has to allocate many objects on the heap for every iteration.

Rope would get an edge if you needed to do many random inserts/deletes in the middle of a very long string.

2017-10-11 15:01:01