I have a web application, as part of it I regularly have to send out "overviews" of records in a database, which contain shortened excerpts of a description-text of that record.
What the code is supposed to do:
- Take an HTML string
- Remove the HTML brackets so that only text remains
- cut it down to
- if there are more than
SHORT_DESCRIPTION_WORD_COUNTwords, add "..." at the end
My current implementation looks like this:
import std/[strutils, strformat, htmlparser, xmltree, enumerate] const SHORT_DESCRIPTION_WORD_COUNT: int = 40 proc truncate*(text: string): string = let cleanedString = text.parseHtml().innerText let splitString = cleanedString.split(" ") if splitString.len() <= SHORT_DESCRIPTION_WORD_COUNT: result = cleanedString else: result.add(splitString[0..SHORT_DESCRIPTION_WORD_COUNT-1].join(" ")) result.add("...")
Looking at some valgrind data, I determined that this proc takes up a sizeable chunk of time and would benefit from being speed-performance optimized a bit.
I'm mostly wondering how to do that though. I believe the intensive steps here are the cleaning up of the HTML and then splitting the string, I'm not sure how to avoid those.