The application uses NCalc to execute diverse calculations.
The 'natural' way to write powers using a computer is using the ^
symbol. However, NCalc already uses it as bitwise or
.
I use the following function to parse calculations and convert it to the Pow(a,b)
format.
Private Function _replacePower(Str As String) As String
Const PowerString As String = "Pow({0},{1})"
Dim i, j As Integer
Dim c As String
Dim before, after, all As String
Dim other_p As Integer 'Keep track of other opening/closing parenthesis, to avoid breaking for a nested one.
other_p = -1
i = 1
While i <= Len(Str)
c = Mid(Str, i, 1)
If c = "^" Then
If Mid(Str, i - 1, 1) = ")" Then
j = i - 1
Do While Mid(Str, j, 1) <> "(" Or other_p > 0
If Mid(Str, j, 1) = ")" Then other_p = other_p + 1
If Mid(Str, j, 1) = "(" Then other_p = other_p - 1
j = j - 1
Loop
before = Mid(Str, j, i - j)
Else
j = i - 1
'The expression to be raised is everything between the power and + - * / , ( <- Opening parenthesis is not ok if there is no closing one, and this case is handled above.
Do While (Mid(Str, j, 1) <> "+" And Mid(Str, j, 1) <> "-" And Mid(Str, j, 1) <> "*" And Mid(Str, j, 1) <> "/" And Mid(Str, j, 1) <> "," And Mid(Str, j, 1) <> "(")
j = j - 1
If j = 0 Then Exit Do
Loop
before = Mid(Str, j + 1, i - j - 1)
End If
other_p = -1
If Mid(Str, i + 1, 1) = "(" Or other_p > 0 Then
j = i + 1
Do While Mid(Str, j, 1) <> ")"
If Mid(Str, j, 1) = ")" Then other_p = other_p - 1
If Mid(Str, j, 1) = "(" Then other_p = other_p + 1
j = j + 1
Loop
after = Mid(Str, i + 1, j - i)
Else
j = i + 1
Do While (Mid(Str, j, 1) <> "+" And Mid(Str, j, 1) <> "-" And Mid(Str, j, 1) <> "*" And Mid(Str, j, 1) <> "/" And Mid(Str, j, 1) <> "," And Mid(Str, j, 1) <> ")")
j = j + 1
If j = Len(Str) + 1 Then Exit Do
Loop
after = Mid(Str, i + 1, j - i - 1)
End If
all = before & "^" & after
Str = Replace(Str, all, String.Format(PowerString, before, after))
i = 1
End If
i = i + 1
End While
Return Str
End Function
My issues lies with performance, as it appears that this function is the bottleneck of the entire application. How could I improve?