Exception HANDLING speed

Hi!
Another question on speed, now concerning exceptions.
I know that exceptions are not the fastest way to notify about an undesired state, but I would rather like to know how fast is to handle an exception.

Let's describe the situation. I have a speed-critical section which is called very often. In this section I call a function where an exception may occur, nevertheless this happens very rarely. So critical for me is the time needed to evaluate whether an exception occurred, not the time needed to throw and catch.

Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
int *foo(int *param) {
  if(*param==RARE_VALUE) throw *param;
  return *param+1;
}

void speedCriticalFunction(int *param) {
  int ret;
  try {
    ret=*foo(param);
  } catch (...) { return; /* Happens really rarely. */ }
  /* ... code ... */
}


So my question is - Is this faster or slower then if I used returning and testing on NULL value if the undesired state happens rarely?

Thanks in advance!
That depends on a state. When it desirable then the speed does not matter.
In general, if an input is 150% clean&relyable then the state must have been detected
prior to it.
For example it is impractical to occupy a calculation with all possible chases, though it
depends on its application.

Of course it depends - that's why I written an example on which I would like to be enlighten.

I'm just interesting what expands to less instructions:
1
2
ret = *foo(param);
if(ret==NULL) then { /* sth */ }

or
1
2
3
try {
  ret = *foo(param);
} catch (...) { /* sth */ }
Probably I should have said, that the section is not speed-critical because of e.g. hardware; just because it is called very very often, but generally with different parameter, so I cannot save time by testing for valid input on another place.
I do not know the expansion except for the catching an occurence.
I suppose prior one would end up in even cumbersome case despite it seems
shorter.
The latter one may or not be caught on an application needs.
I prefer re-raise.
hello yman,

well, 'if' is the most simple command that exists in C/C++. while 'throw, ty, catch' is the most complicated.

I'd say that nothing is faster than a simple if(x). but that's just my humble opinion

Btw

if(ret==NULL) then { /* sth */ } <- Bug
return *param+1; <- Bug
Handling exception slower then simple testing returning value. Be aware that SEH is OS feature and OS decide to call exception handler. Every time you call foo() the new exception handler added in chain and removed before function returns. Fortunately adding and removing exception handler are fast operations.
But i'm not sure that you really need to use SEH in this situation.

coder777 +1 ;-)
Last edited on
Well, before boolivar wrote the information that looks more inside, I couldn't be sure, so I've created a small testing program, which verified what boolivar said. Testing on NULL is faster then handling exception, nevertheless the difference is not as big if the exception is rare. On the other side, if exception raises often, it is much slower then NULL tests.

Thank you all!

Here's the code of testing app:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <cstdio>
#include <ctime>

//******************************************************************************

#define CEIL      10000000
#define RARE       9999999
#define OFTEN       999999

//******************************************************************************

int *rareExceptionTest(int *param) {
	if(*param >= RARE) throw *param;
	return param;
}

//******************************************************************************

int *oftenExceptionTest(int *param) {
	if(*param >= OFTEN) throw *param;
	return param;
}

//******************************************************************************

int *rareNullTest(int *param) {
	if(*param >= RARE) return NULL;
	return param;
}

//******************************************************************************

int *oftenNullTest(int *param) {
	if(*param >= OFTEN) return NULL;
	return param;
}

//******************************************************************************

int main(int argc, char *argv[]) {
	long int start;
	int *ret;
	int sum=0;
	
	start = clock();
	for(int i=0; i<CEIL; i++) {
		try {
			ret = rareExceptionTest(&i);
			sum += *ret;
		}catch (...) {}
	}
	printf("rare exception:  elapsed %10ld ticks (sum=%d)\n", clock()-start, sum);
	
	sum=0;
	start = clock();
	for(int i=0; i<CEIL; i++) {
		ret = rareNullTest(&i);
		if(ret) sum+=*ret;
	}
	printf("rare null:       elapsed %10ld ticks (sum=%d)\n", clock()-start, sum);
	
	sum=0;
	start = clock();
	for(int i=0; i<CEIL; i++) {
		try {
			ret = oftenExceptionTest(&i);
			sum += *ret;
		}catch (...) {}
	}
	printf("often exception: elapsed %10ld ticks (sum=%d)\n", clock()-start, sum);
	
	sum=0;
	start = clock();
	for(int i=0; i<CEIL; i++) {
		ret = oftenNullTest(&i);
		if(ret) sum+=*ret;
	}
	printf("often null:      elapsed %10ld ticks (sum=%d)\n", clock()-start, sum);
	
	return 0;
}


And here's the output:

rare exception:  elapsed     310000 ticks (sum=-2024260031)
rare null:       elapsed     100000 ticks (sum=-2024260031)
often exception: elapsed  148160000 ticks (sum=1782293665)
often null:      elapsed      90000 ticks (sum=1782293665)
I don't think anyone has answered the real question.

A catch() block does not have to "determine" whether or not an exception occurred. If an exception is thrown, it
executes. If no exception is thrown, it does not execute. Therefore, catch() is faster at "determining" whether
or not an exception was thrown.

Now the process of throwing the exception and unwinding the stack to find the catch() block will definitely
be slower than a simple if() check, as yman's test showed.
I think the more important question to ask is under what scenario we use a simple if for test and under what scenario we use try/catch statement since it is more 'costly'.

My own personal opinion is try/catch is for use for more "serious" error like IO or network. For API failing, a simple if to check return code is enuff.

In Java, the API make it mandatory failing is to throw exception so we have no choice but to use try/catch. In C++ once again, it is flexible and leave that decision to us programmers :)
Sutter and Alexandrescu in C++ Coding Standards, Item 42 (Prefer to use exceptions to report errors), page 143
offer this advice:

"In rare cases, consider using an error code [instead of exceptions] if you are certain that both of the following
are true:

* The benefits of exceptions don't apply: For example, you know that nearly always the immediate caller
must directly handle the error and so propagation should happen either never or nearly never...

* The actual measured performance of throwing an exception over using an error code matters..."
closed account (EzwRko23)

In Java, the API make it mandatory failing is to throw exception so we have no choice but to use try/catch. In C++ once again, it is flexible and leave that decision to us programmers :)


Huh? Java exception system is just as flexible a that of C++ (and I would risk saying it is even more flexible: because of the finally clause, checked/unchecked distinction, and because it is much simpler to get exception safety right). And definitely you are never forced to use a try/catch. I really don't know, where you guys get these things from.


I think the more important question to ask is under what scenario we use a simple if for test and under what scenario we use try/catch statement since it is more 'costly'.


If you have to perform many tests in a single method, then exceptions are cheaper (if thrown rarely). If just one, the cost of installing SEH is larger than simple condition checking.
Last edited on
And definitely you are never forced to use a try/catch. I really don't know, where you guys get these things from.


I am referring to some Java SDK API where the Javadoc explicitly say calling this method may throw say ABCException. In my Java code, when I call that method I need to have a try/catch ABCException or to their grandfather Exception class else during compilation javac will complain. This is what I say it "force" us to use try/catch under this scenario.
That isn't a bad thing in itself, though.
closed account (EzwRko23)

In my Java code, when I call that method I need to have a try/catch ABCException or to their grandfather Exception class else during compilation javac will complain.


You don't have to. You can just declare your method as "throws ABCException", and you get an identical behaviour to that of C++.
Last edited on
Topic archived. No new replies allowed.