31

I'm using Coldfusion. I want to concatenate two strings into the same struct key, but I keep getting an error of "can't convert x into a boolean."

For example:

<cfset myStruct.string1 = nodes[1].string1.XmlText>
<cfset mystruct.string2 = nodes[1].string2.XmlText>

Neither of the following works

<cfset myStruct.concatendatedSring = nodes[1].string1.XmlText AND nodes[1].string2.XmlText>
<cfset myStruct.concatendatedSring = myStruct.string1 AND myStruct.string2>

Why does neither method work?

Mohamad
  • 34,731
  • 32
  • 140
  • 219

3 Answers3

60

& is the string concat operator, AND and && are boolean operators.

<cfset myStruct.concatendatedSring = myStruct.string1 & myStruct.string2>
Henry
  • 32,689
  • 19
  • 120
  • 221
13

I've done a number of informal tests on CF10 through 4 different ways to concatenate strings and the results are surprising. I did 50k iterations of appending "HELLO" in various ways. I've includes some rough data below in order from slowest to quickest. These numbers were consistent across 10 different requests, hence the average:

string1 = "#string1##string2#"; // ~4800ms
string1 = string1 & string2; // ~ 4500ms
string1 &= string2; // ~4200ms

string1 = createObject("java",  "java.lang.StringBuffer").init();
string1.append(string2); // ~250ms

These fall in the order that I expected, but was surprised at how much quicker the StringBuffer was. I feel you're going to get the most out of this when concatenating large arounds of String data, such as a CSV or similar. There's no detailed test I performed that weighed one option over the other in typical one-off operations.

Tristan Lee
  • 1,210
  • 10
  • 17
  • StringBuffer has the added advantage that it does not try to convert strings that look like numbers to integers (which can fail if the string is longer than the permissible length for an integer). – Ectropy Aug 05 '20 at 15:00
  • does not make sense. string assignment and concatenation take more than 4 seconds !!?? looks like you have an additional 0 in your test results. – murphy1310 Sep 29 '21 at 22:31
10

In addition to Henry's answer, you can also concatenate two strings like this:

<cfset myStruct.concatendatedSring="#myStruct.string1##myStruct.string2#">
Gert Grenander
  • 16,866
  • 6
  • 40
  • 43
  • 2
    I did an informal test on Cf9 in the last couple of weeks, and was surprised to find that this method is *significantly* slower for a single concatenation. It's almost as bad for two. I think it is because of how CF handles execution areas, but that's a guess. – Ben Doom Sep 02 '10 at 12:57