Skip to content

Instantly share code, notes, and snippets.

@devoyster
devoyster / ProtobufExample.cs
Created December 13, 2011 21:20
protobuf-net plain example
// Explicit proto contract
[ProtoContract]
public class MappedEntity
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
}
@devoyster
devoyster / ProtobufAutoContract.cs
Created December 13, 2011 21:24
protobuf-net registering type at runtime
var model = RuntimeTypeModel.Default;
// Obtain all serializable types having no explicit proto contract
var serializableTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.IsSerializable && !Attribute.IsDefined(t, typeof(ProtoContractAttribute)));
foreach (var type in serializableTypes)
{
var metaType = model.Add(type, false);
metaType.AsReferenceDefault = true;
@devoyster
devoyster / Protobuf.txt
Created December 13, 2011 21:25
protobuf-net performance tests
Serialization of 90 objects, 1000 iterations:
Write(ms) Read(ms) Size(bytes)
BinaryFormatter 634 517 9807
protobuf-net v2 219 253 5179
@devoyster
devoyster / VariablesReductionVisitor.cs
Created December 14, 2011 21:04
LambdaExpression visitor which reduces variables by transforming them to constants (if possible)
public class VariablesReductionVisitor : ExpressionVisitor
{
private List<Expression> _children;
public override Expression Visit(Expression node)
{
// Preserve parent's child expressions collection
var siblings = _children;
_children = new List<Expression>();
// Here different expression keys should be generated since parameter "value" is different
// for two expressions at the moment of their creation
int value = 1;
Expression<Func<string, string>> expr1 = s => s.Length > value ? s.Substring(0, value) : s;
int value = 2;
Expression<Func<string, string>> expr2 = s => s.Length > value ? s.Substring(0, value) : s;
// Here same expression keys should be generated since parameter value (1) is the same
// for two expressions at the moment of their creation
@devoyster
devoyster / EnumerableForEach.cs
Created December 22, 2011 20:50
LINQ to Objects ForEach()
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
foreach (T item in source)
{
action(item);
}
@devoyster
devoyster / OldStyleArgChecks.cs
Created January 2, 2012 17:19
VerifyArgs blog post
public void MyMethod(string str)
{
CheckUtil.NotNullOrEmpty(str, "str");
}