0

I think this may be overkill, but I am just curious. Generally speaking (if there is a general answer), which is faster assuming the strings are equal to each other 50% of the time:

void UpdateString1(string str1, string str2)
{
    str1 = str2;
}

void UpdateString2(string str1, string str2)
{
    if (str1 != str2)
    {
        str1 = str2;
    }
}
Evorlor
  • 7,263
  • 17
  • 70
  • 141

2 Answers2

1

Assuming in your hypothetical language != means "compare" and = means "copy"...

I'm going to say that UpdateString1 is always at least as fast.

Suppose the strings aren't equal. Then UpdateString2 performs the comparison as well as the assignment. So it does additional work.

Suppose the strings are equal. Then the comparison involves iterating through every single character in both strings and comparing them. So that's O(n). Similarly, copying would involve, at worst, visiting every character in one string and copying it to the second. Also O(n). So the same complexity. Also the same number of memory accesses.

However you've also got the partial comparison costs of the strings that aren't equal. Which I think tips it in favour of the copy.


Supposing != and = were just comparing or updating references by identity, not by value...

All operations are O(1) and simuilar in cost. The = is one operation 100% of the time. The !=/= is an expected 1.5 operations if strings are equal 50% of the time.

Tommy
  • 99,986
  • 12
  • 185
  • 204
0

If you really wanted to check if str1 != str2, then use str1 = str2;.

  1. It is shorter in the code and easier to follow.
  2. Branches add more complexity than assignments. If assignment is considered 1 operation unit, the branch is probably 1.5 operation units on its own on average, and even more if your data passed in is random. See: Why is it faster to process a sorted array than an unsorted array?
  3. It is overkill to optimize for this.
Community
  • 1
  • 1
nmore
  • 2,474
  • 1
  • 14
  • 21
  • i meant pass by value. my bad. also, was not looking for a java specific answer. my syntax was just fine – Evorlor Aug 26 '14 at 23:52