📜 ⬆️ ⬇️

Crouching Tiger, Hidden Dragon

Java vs. C # ... What could be better than an eternal argument? No, this article is not devoted to the next benchmark, and it is not even holy war, there is not even a question: “who is better”.

For each task there is a tool. Compare C # and Ruby, for example, does not make sense, because their purpose is completely different, and nature also. However, C # and Java are the closest ones in their philosophy.

Very often, colleagues writing in Java are not even aware of many (!!!) things provided by (or, conversely, not provided) C #.
')
If it is interesting for you to look at C # and Java without subjectivity , and also to learn the internal structure of this or that opportunity, then go ahead.

â–Ś A bit of history


The C # language appeared in 2001, and its development was started back in 1999. Then it was very similar to Java 1.4. However, modern C #, which we know, should start being viewed from version 2.0 (which corresponds to the Java 5 release time).

There is an opinion that C # borrows a lot from Java. However, I strongly disagree with this. In my opinion, C # is in many ways C “with objects”, or C ++ “with a human face”.

I hope that the article and the arguments in it will confirm this statement.
I will not retell Wikipedia . Therefore, we will immediately move on and take a look at the key differences and advantages.

First we look at the capabilities of the JVM and the common language runtime (CLR), then we’ll look at C # syntax sugar.

â–Ś Episode I: Bytecode


Both .NET and Java use bytecode. Of course, besides the format itself, there is one very important difference - polymorphism.

CIL (Common Intermediate Language, aka MSIL, aka IL) is a byte-code with polymorphic (generalized) instructions.

So, if Java uses a separate instruction for each type of operations with different types (for example: fadd is the addition of 2 floats, iadd is the addition of 2 integers ), then in CIL for each type of operations there is only one instruction with polymorphic parameters ( for example, there is only one instruction - add , which produces addition and float, and integer). The issue of solving the generation of the corresponding x86 instructions falls on the JIT.

The number of instructions on both platforms is about the same. Comparing the list of Java bytecode and CIL commands, it is clear that Java is 206, and CIL is 232, but do not forget that many Java commands simply repeat each other’s functions.

â–Ś Episode III: Generics (parameterized types || parametric polymorphism)


As you know, Java uses the type erasure mechanism, i.e. generics support is provided only by the compiler, but not runtime, and after compilation information about the type itself will not be available.

For example, the code:

List<String> strList = new ArrayList<String>();
List<Integer> intList = new ArrayList<Integer>();

bool areSame = strList.getClass() == intList.getClass();
System.out.println(areSame);

true.

T java.lang.Object.

List<String> strList = new ArrayList<String>();
strList.add("stringValue");

String str = strList.get(0);

:

List list = new ArrayList();
list.add("stringValue");
String x = (String) list.get(0);

, .

.NET, , generics compile-time, run-time.

generics Java? , .NET’a:


.. generics , . boxing/unboxing.

â–Ś IV: Types


Java -. . : (integer, float ..) java.lang.Object. generics Java primitive types.

- - everything is object.

. .

C# . – struct.

:

public struct Quad
{
    int X1;
    int X2;
    int Y1;
    int Y2;
}

generics C# value types (int, float ..)

Java :

List<Integer> intList = new ArrayList<Integer>(); 

:

List<Integer> intList = new ArrayList<int>(); 

C# .

.NET.

.NET 3 : value, reference pointer types.

, value type – primitive type Java. System.Object, , ( : value type , , boxing).

Reference type – , reference types Java.

Pointer type – .NET’a. , CLR !

:

struct Point
{
    public int x;
    public int y;
}

unsafe static void PointerMethod()
{
    Point point;
    Point* p = &point;
    p->x = 100;
    p->y = 200;

    Point point2;
    Point* p2 = &point2;
    (*p2).x = 100;
    (*p2).y = 200;
}

C++ , ?

â–Ś V: C#


, C#:

C# , .. GetXXX, SetXXX. , object.PropertyX, object.GetPropertyX.

:

public class TestClass
{
    public int TotalSum
    {
        get
        {
            return Count * Price;
        }
    }

    //  -    
    public int Count
    {
        get; 
        set;
    }

    public int Price
    {
        get
        {
            return 50;
        }
    }
}

:

public class TestClass
{

    /*
    *  
    */
    private int <Count>k__BackingField;
    //  -    
    public int Count
    {
        get { return <Count>k__BackingField; }
        set { <Count>k__BackingField = value; }
    }
}

C/C++. . – callback , .

.NET – .

DLR (Dynamic Language Runtime – .NET), dynamic C# 4 – . C# dynamic.

Da Vinci Java, .. VM.

C#:

public class TestClass
{
    public delegate int BinaryOp(int arg1, int arg2);

    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Multiply(int first, int second)
    {
        return first * second;
    }

    public void TestDelegates()
    {
        BinaryOp op = new BinaryOp(Add);
        int result = op(1, 2);
        Console.WriteLine(result);
        //: 3

        op = new BinaryOp(Multiply);
        result = op(2, 5);
        Console.WriteLine(result);
        //: 10
    }
}

C:

int Add(int arg1, int arg2) 
{
    return arg1 + arg2;
}

void TestFP() 
{
     int (*fpAdd)(int, int); 
     fpAdd = &Add; //  
     int three = fpAdd(1, 2); //    
}

, ? C ( float arg1, float arg2), C# — . C# , .

- . , EventDispatcher’, Publisher/Subscriber. . .

:

public class MyClass
{
    private string _value;

    public delegate void ChangingEventhandler(string oldValue);

    public event ChangingEventhandler Changing;

    public void OnChanging(string oldvalue)
    {
        ChangingEventhandler handler = Changing;
        if (handler != null) 
            handler(oldvalue);
    }

    public string Value
    {
        get
        {
            return _value;
        }
        set
        {
            OnChanging(_value);
            _value = value;
        }
    }

    public void TestEvent()
    {
        MyClass instance = new MyClass();
        instance.Changing += new ChangingEventhandler(instance_Changing);
        instance.Value = "new string value";
        //   instance_Changing
    }

    void instance_Changing(string oldValue)
    {
        Console.WriteLine(oldValue);
    }
}

– , .. .

:

public class TestClass
{
    public delegate int BinaryOp(int arg1, int arg2);

    public void TestDelegates()
    {
        BinaryOp op = new BinaryOp(delegate(int a, int b)
                                   {
                                       return a + b;
                                   });
        int result = op(1, 2);
        Console.WriteLine(result);
        //: 3
    }
}

?

-.

- — , , .

public class TestClass
{
    public delegate int BinaryOp(int arg1, int arg2);

    public void TestDelegates()
    {
        BinaryOp op = new BinaryOp((a, b) => a + b);
        int result = op(1, 2);
        Console.WriteLine(result);
        //: 3
    }
}

? :

public class MyClass
{
    /*
     *   
     */

    public void TestEvent()
    {
        MyClass instance = new MyClass();
        instance.Changing += (o) => Console.WriteLine(o);
        instance.Value = "new string value";
        //  Console.WriteLine
    }
}

, (!!!). , C# , .. .

-, LINQ (Language Integrated Query).

LINQ? MapReduce LINQ?

public static class MyClass
{
    public void MapReduceTest()
    {
        var words = new[] {"...some text goes here..."};
        var wordOccurrences = words
            .GroupBy(w => w)
            .Select(intermediate => new
            {
                Word = intermediate.Key,
                Frequency = intermediate.Sum(w => 1)
            })
            .Where(w => w.Frequency > 10)
            .OrderBy(w => w.Frequency);
    }
}

SQL- :

public void MapReduceTest()
{
    string[] words = new string[]
        {
            "...some text goes here..."
        };
    var wordOccurrences =
        from w in words
        group w by w
        into intermediate
        select new
            {
                Word = intermediate.Key,
                Frequency = intermediate.Sum((string w) => 1)
            }
        into w
        where w.Frequency > 10
        orderby w.Frequency
        select w;
}

LINQ (GroupBy().Select().Where() ..), –

new
    {
        Word = intermediate.Key,
        Frequency = intermediate.Sum(w => 1)
     }

… ? – .

var. C++ 11 auto.

:

public void MapReduceTest()
{
    string[] words = new string[] { "...some text goes here..." };
    var wordOccurrences = Enumerable.OrderBy(Enumerable.Where(Enumerable.Select(Enumerable.GroupBy<string, string>(words, delegate (string w) {
        return w;
    }), delegate (IGrouping<string, string> intermediate) {
        return new { Word = intermediate.Key, Frequency = Enumerable.Sum<string>(intermediate, (Func<string, int>) (w => 1)) };
    }), delegate (<>f__AnonymousType0<string, int> w) {
        return w.Frequency > 10;
    }), delegate (<>f__AnonymousType0<string, int> w) {
        return w.Frequency;
    });
}

[ ]

C#, .. .

, C# 5 – , , C++ 11!

â–Ś


C# Java , (.NET Java). — .

C# — Java. Microsoft, COOL (C-like Object Oriented Language). C/C++? .

, ( ) , .

!

Source: https://habr.com/ru/post/145932/


All Articles