Created
August 30, 2016 17:12
-
-
Save evilmucedin/517ec224e3cfec05f0da11ceb9a715c7 to your computer and use it in GitHub Desktop.
This file contains 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
// mcs -unsafe -debug- Spaces.cs; time mono -O=all ./Spaces.exe | |
using System; | |
using System.Threading.Tasks; | |
public class Spaces { | |
static unsafe string GetTest(int len) { | |
var s = new string(' ', len); | |
fixed (char* pS = s) { | |
for (int i = 0; i < len; ++i) { | |
pS[i] = (char)('0' + (i % 10)); | |
} | |
} | |
return s; | |
} | |
public static void Main(string[] args) { | |
var s = GetTest(1000000); | |
string r; | |
int totalLen = 0; | |
for (int i = 0; i < 10; ++i) { | |
r = InjectSpaces(s); | |
totalLen += r.Length; | |
} | |
Console.WriteLine("Total length: {0}", totalLen); | |
//Console.WriteLine("'{0}' -> '{1}'", s, r); | |
} | |
static unsafe string InjectSpaces(string s) { | |
fixed (char* pS = s) { | |
var pLength = (int*)pS - 1; | |
var length = *pLength & 0x3fffffff; | |
var result = new string(' ', 2*length - 1); | |
fixed (char* pResult = result) { | |
for (int i = 0; i < length; ++i) { | |
pResult[2*i] = pS[i]; | |
} | |
} | |
return result; | |
} | |
} | |
static string InjectSpaces2(string s) { | |
var ra = new char[s.Length * 2 - 1]; | |
ra[0] = s[0]; | |
Parallel.For(1, s.Length, (i) => { | |
ra[2*i - 1] = ' '; | |
ra[2*i] = s[i]; | |
}); | |
return new string (ra); | |
} | |
static string InjectSpaces3(string s) { | |
var ra = new char[s.Length * 2 - 1]; | |
ra[0] = s[0]; | |
for (int i = 1; i < s.Length; ++i) { | |
ra[2*i - 1] = ' '; | |
ra[2*i] = s[i]; | |
} | |
return new string (ra); | |
}} | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
static string InjectSpaces(const string& s) { | |
string result(2*s.length() - 1, ' '); | |
char* pResult = (char*)result.data(); | |
const char* pS = s.data(); | |
const auto length = s.length(); | |
for (auto i = 0; i < length; ++i) { | |
pResult[2*i] = pS[i]; | |
} | |
return result; | |
} | |
int main() { | |
string s(1000000, ' '); | |
char* pS = (char*)s.data(); | |
for (size_t i = 0; i < s.length(); ++i) { | |
s[i] = '0' + (i % 10); | |
} | |
string result; | |
int totalLength = 0; | |
for (size_t i = 0; i < 10; ++i) { | |
result = InjectSpaces(s); | |
totalLength += result.length(); | |
} | |
cout << totalLength << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment