TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# If Versus Switch Performance

Compare the performance of if and switch statements. Describe how to select the fastest one.
If, switch. If and switch have different performance. Knowing some of the performance details is useful. Some programs can benefit.IfSwitch
Notes, benchmarks. We compare the performance of if-statements and switch-statements. Choosing the best statement type depends on the data we are testing.Optimization
Benchmark. This program declares 2 methods that are tested. The results of the 2 methods on all inputs are equivalent—they have the same effects.

Version 1: This version is called IsValidIf—it implements a selection with several if-statements.

Version 2: This version of the code is called IsValidSwitch—it implements a selection as a switch.

Result: The switch statement method (version 2) is faster. So for the input ints here, using switch is a performance improvement.

Info: If you look at the intermediate code here, you will see that the switch uses a jump table opcode.

C# program that times if and switch methods using System; using System.Diagnostics; class Program { static bool IsValidIf(int i) { // Uses if-expressions to implement selection statement. if (i == 0 || i == 1) { return true; } if (i == 2 || i == 3) { return false; } if (i == 4 || i == 5) { return true; } return false; } static bool IsValidSwitch(int i) { // Implements a selection statement with a switch. switch (i) { case 0: case 1: return true; case 2: case 3: return false; case 4: case 5: return true; default: return false; } } const int _max = 100000000; static void Main() { bool b; var s1 = Stopwatch.StartNew(); // Version 1: use if-statement. for (int i = 0; i < _max; i++) { b = IsValidIf(i); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use switch-statement. for (int i = 0; i < _max; i++) { b = IsValidSwitch(i); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.Read(); } } Output 3.83 ns [if] 2.88 ns [switch]
Benchmark, fast path. This benchmark tests 2 implementations. The methods receive the value zero 60% of the time. They receive the value one 40% of the time.

Version 1: This version of the code uses a switch statement. All of the cases are tested with equal priority (none is tested first).

Version 2: This code uses an if-else construct. The first int tested is 0, which gives it priority over other tests.

Result: Method2 is most optimized for the value zero because it tests for it first. This method, which uses if, is faster.

Info: The IL reveals that the switch-statement uses a "switch" opcode. The if-statements simply use branch opcodes.

C# program that benchmarks switch, if, fast path using System; using System.Diagnostics; class Program { const int _max = 100000000; static void Main() { Method1(0); // JIT. Method2(0); // JIT. var s1 = Stopwatch.StartNew(); // Version 1: use switch. for (int i = 0; i < _max; i++) { Method1(0); Method1(0); Method1(0); Method1(0); Method1(0); Method1(0); Method1(1); Method1(1); Method1(1); Method1(1); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use if, fast path. for (int i = 0; i < _max; i++) { Method2(0); Method2(0); Method2(0); Method2(0); Method2(0); Method2(0); Method2(1); Method2(1); Method2(1); Method2(1); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.Read(); } static int Method1(int val) { switch (val) { case 0: { return 1; } case 1: { return 3; } default: { throw new Exception(); } } } static int Method2(int val) { if (val == 0) { return 1; } if (val == 1) { return 3; } throw new Exception(); } } Output 39.81 ns [switch] 18.79 ns [if]
Notes, switch slower. It is tempting to think that a switch is always faster than an equivalent if-statement. However, this is not true.

And: A situation where the switch is slower is when the actual runtime of the program has a very skewed distribution of inputs.

Benchmark

So: If the input is almost always a specific value, then using an if-statement to test for that value may be faster.

A summary. Sometimes a switch statement is slower than an if-statement. Using frequency heuristics, you can optimize a fast path with an if-statement in many programs.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf