Skip to content

Exception try catch performance 10 times low than java #12892

@chrishaly

Description

@chrishaly

A compare test did, result says: performance of try catch throw Exception in .Net is over 10 times slow than in Java.

Reproduce:

C# code

    class ExceptionPerformanceTest
    {
        public void Test()
        {
            var stopwatch = Stopwatch.StartNew();
            ExceptionTest(100_000);
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
        }

        private void ExceptionTest(long times)
        {
            for (int i = 0; i < times; i++)
            {
                try
                {
                    throw new Exception();
                }
                catch (Exception ex)
                {
                    //Ignore
                }
            }
        }
    }

Java Code

public class ExceptionPerformanceTest {

    public void Test() {
        Instant start = Instant.now();
        ExceptionTest(100_000);
        Instant end = Instant.now();
        Duration duration = Duration.between(start, end);
        System.out.println(duration.toMillis());

    }

    private void ExceptionTest(long times) {
        for (int i = 0; i < times; i++) {
            try {
                throw new Exception();
            } catch (Exception ex) {
                //Ignore
            }
        }
    }
}

Test Result:

.Net: 2151ms
Java: 175ms

2151/175=12.29

source code at https://github.com/chrishaly/DotNetVsJavaPerformanceTest

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions