Last active
November 30, 2022 06:10
-
-
Save xoofx/56f23cf2820ff5bade461fdf18d6c933 to your computer and use it in GitHub Desktop.
Fast decode a string IP address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Related to this benchmark article https://stebet.net/benchmarking-and-performance-optimizations-in-c-using-benchmarkdotnet/ | |
| public static class IP2Locationxoofx | |
| { | |
| public static uint IPAddressToInteger(string input) | |
| { | |
| uint ipAddress = 0; | |
| uint acc = 0; | |
| // Note: we assume that the string is well formed | |
| foreach (var c in input) | |
| { | |
| if (c == '.') | |
| { | |
| ipAddress = (ipAddress << 8) | acc; | |
| acc = 0; | |
| } | |
| else | |
| { | |
| acc = acc*10 + (uint)(c - '0'); | |
| } | |
| } | |
| ipAddress = (ipAddress << 8) | acc; | |
| return ipAddress; | |
| } | |
| } | |
| // Results: | |
| // | |
| // Method | Median | StdDev | Gen 0 | Gen 1 | Gen 2 | Bytes Allocated/Op | | |
| // ------------------------ |------------ |---------- |------- |------ |------ |------------------- | | |
| // BenchIP2LocationHelper7 | 270.6996 ns | 1.5360 ns | 585.00 | - | - | 61.62 | | |
| // BenchIP2Locationxoofx | 17.3949 ns | 0.1378 ns | - | - | - | 0.00 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment