What's the right way to reverse a string?

I have some long strings that I need to reverse. I haven’t found a string function for this, so I wrote my own partial which is (unsurprisingly) very slow but does the job.

{{- return delimit (collections.Reverse (split . "")) "" }}

Is there a more performant way to do this?

This seems to be about 20% faster (test was 1000 iterations).

{{ $s := "" }}
{{ range split . "" }}
  {{ $s = print . $s }}
{{ end }}
{{ return $s }}

But the partial call is the largest portion (~ 85%) of the total time. Can you inline the code instead?

Thanks Joe. Yes, I can inline the partial and it is a good tad (around 50%) faster. But not as much as I liked it to be.

Would it be faster if Hugo would provide a built-in function for strings?

Sorry, I didn’t mean to create an inline partial. I was wondering if you could just insert the code where needed. It may not be DRY, but it’s fast.

Regarding a template function to reverse strings… I would think it would be faster, but I’m not sure.

Also, I changed the example above to use print instead of add… it’s a bit faster.

1 Like

I tried out your suggestion. It’s a game changer. Thanks a lot!

Looking at the Go issue queue, there have been a few requests for a strings.Reverse function, but all were closed due to insufficient need.

https://github.com/golang/go/issues/36887#issuecomment-591601541

It remains not needed often enough to merit inclusion in the standard library.

I reached the same conclusion, and would vote to not create a template function. The implementation is not trivial… you need to handle both composite and non-composite characters .

So… which method is faster depends on the length of the string. For a long string (e.g., a paragraph), the split/delimit approach is faster. For short strings (e.g., a word) the range/print approach is faster.

Hmm … Oh, well, I would say that collections.Reverse should support strings (which is effectively a byte slice), could you reaise a GH issue.

1 Like

Done.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.