optimizedDeepEquals function

bool optimizedDeepEquals(
  1. Object? a,
  2. Object? b
)

Compare two json-like objects for equality a and b must be one of

  • null
  • num
  • bool
  • String
  • List of above types
  • Map of above types

This is an alternative too DeepCollectionEquality().equals, which is very slow and has O(n^2) complexity:

Implementation

bool optimizedDeepEquals(Object? a, Object? b) {
  if (identical(a, b)) {
    return true;
  }
  if (a == b) {
    return true;
  }
  if (a is Map) {
    if (b is! Map) {
      return false;
    }
    if (a.length != b.length) return false;
    for (var key in a.keys) {
      if (!b.containsKey(key)) return false;
      if (!optimizedDeepEquals(a[key], b[key])) return false;
    }
    return true;
  }
  if (a is List) {
    if (b is! List) {
      return false;
    }
    final length = a.length;
    if (length != b.length) return false;
    for (var i = 0; i < length; i++) {
      if (!optimizedDeepEquals(a[i], b[i])) return false;
    }
    return true;
  }
  return false;
}