I am creating an XML file using a program that applies Freemarker commands (but version is 2.3.20 so rather old and limited).
There is a list
type, but it is immutable. Although concatenation is possible, the doc warns about the resulting list being slow:
Note that sequence concatenation is not to be used for many repeated concatenations, like for appending items to a sequence inside a loop. It's just for things like <#list users admins as person>. Although concatenating sequences is fast and is constant time (it's speed is independently of the size of the concatenated sequences), the resulting sequence will be always a little bit slower to read than the original two sequences were. Thus, after tens or hundreds of repeated concatenations the result can be impractically slow to reader.
Therefore, the solution to concatenate one by one might be slow; however I wonder if slowness only affects retrieval of elements by index like mylist[7]
, or also iteration like <#list mylist as element><#/list>
.
So my current solution is to build a string dynamically and split it:
<#assign short_names>
<#list source_list as element>
${element?substring(0,3)}
</#list>
</#assign>
<#assign short_names = short_names?word_list>
Is there a better way? In particular, this technique prohibits operations on the partially constructed short_names
as a list, such as checking that an element is not already contained.
Note that in my use case, the list actually has at most 25 elements.
CodePudding user response:
FreeMarker isn't for data processing of this kind. I recommend solving such processing in Java. When the data can't be already in the desirable form in the data-model (aka. template context), you can have some utility classes that you call from the template to do these operations.
As of the speed of just listing concatenated lists, it has the same performance penalty as directly accessing by index. Now, that possibly doesn't matter in most applications if it's just some tens of list concatenated, but concatenation just wasn't meant to be used for building a new list from many small pieces.