by pavlov · 11y ago · 0 comments
Here's a practical example... Imagine an editor where an on-screen element is deleted. The controller might do a bunch of stuff such as:
element.parent = nil
scene.clearReferencesToElement(element)
container.delete(element)
self.selection = []
If there's a listener on "container", it will get notified even before the selection was cleared. That's probably not the intention.If we know that's going to happen, we could move the selection manipulation before the container access... But then we have fragile code that depends on implicit behavior in a model class. Always better to send an explicit event.
The main reason was that it made composition pretty sane and created clear places to handle changes. With KVO, you implement your KVO-compliant mutation methods, and all changes would then get funneled through there (most notable container ones). Compare the mess that is NSView (addSubview/insertSubview:positioned:relativeTo:/removeFromSuperview/etc) to the post-KVO NSTreeNode. NSTreeNode simply exposes .mutableChildNodes, which you treat as a normal array (addObject:/etc) and after adding a child, it then has parentNode set to the parent after. This was great for lots of reasons: 1. No need to re-create API, you just used NSMutableArray's existing API. So [someNode.mutableChildNodes removeObjectsWithPredicate:somePredicate] and all the parentNode relationships get handled for free. Compare this to pre-KVO methods where every time you wanted to take advantage of a neat NSMutableArray feature, you'd have to re-expose it yourself like removeSubviewsWithPredicate:, or wind up having to copy out the array, mutate, then re-assign with setSubviews: 2. Less room for error since all your cleanup code just happens in removeObjectFrom<Key>AtIndex:, one funnel.
Again, I believe this to be a great local maxima for this style of programming, one that was never that fully explored since the move to more KVO-ness was eclipsed by the attention to iOS. I think most the problems are better solved through React's top-down approach.
However, what is true is that:
1. Both JS and the DOM are fast enough that you can lay out most reasonable pages within the threshold of visual perception (~150-200ms).
2. If you need to layout the page during an animation frame, you're hosed anyway. You have a frame budget of 16.67ms and layout will take 100ms+ on mobile.
And so the practical, qualitative conclusion is the same: you can use React for your basic page transformations & rendering, but you need to use CSS transforms and offload the work to the GPU if you want to have a prayer of making animations work on mobile. And React also protects you from completely fucking up performance (which is trivially easy with JQuery), so many real-world pages from inexperienced webdevs experience a very significant speedup.
If you use something like Immutable.js you can avoid a lot (most? all?) of the diffing since comparing trees of objects becomes a simple object reference comparison. This is common in the Om world, and becoming more popular in JS too.
We then switched to exploring more standard approaches like having individual components monitor the relevant model events and manage their own state, using React's rendering model at a much finer granularity. We haven't finished our investigations yet and there are some other concerns about React's performance under certain conditions, but so far, the finer-grained approach seems more promising and is our most likely way forward for this particular project.
If you wanted to be more adventurous you should look at alternative virtual dom implementations http://vdom-benchmark.github.io/vdom-benchmark/. What you'll find is that React is actually the slowest one out there based on performance. For instance, on dbmonster InfernoJS sees 50-100% more fps and on my machine ~20x better benchmark performance. If you want the next popular implementations look at virtual-dom, which is leveraged in a variety of frameworks like https://github.com/ashaffer/vdux, or Google's Incremental DOM, https://github.com/google/incremental-dom.
That's really not how you'd write a large idiomatic React application.
Conceptually, you should be running render() methods on the actual items which have changed, and a very small number of parent components with little-to-no DOM elements. You should also be executing a relatively small number of shouldComponentUpdate() methods which should be extremely fast to execute.
If you are doing that, then where exactly was the performance bottleneck, and how was your alternative approach avoiding it? I mean, sure, if there's simply no possible way for you to figure out what to re-render cheaply, then your app will have poor performance. But that doesn't seem to be true from your other comments.
In fact, it sounds like your second approach might be closer to a normal idiomatic React app than your first implementation. Incidentally, are you using some sort of flux architecture?
React docs oversell this point a bit: https://facebook.github.io/react/docs/multiple-components.ht...
"You may be thinking that it's expensive to change data if there are a large number of nodes under an owner. The good news is that JavaScript is fast and render() methods tend to be quite simple, so in most applications this is extremely fast. Additionally, the bottleneck is almost always the DOM mutation and not JS execution. React will optimize this for you by using batching and change detection. [...] Don't underestimate how fast JavaScript is relative to the DOM."
React isn't magically fast, it's just O(n_size_of_diff). Getting it to perform well here requires you to figure out how to prune the size of the diff. You're doing it by splitting the app state into finer grained trees (each tree is pruning the branches it's not listening to) but any gains you're picking up from doing this could be done on the single root solution with appropriate shouldComponentUpdate methods.
The alternative (and easier) way of reducing the diff size is to simply window your data before passing it into the render, which can work for things like grids and lists but doesn't sound like your problem.
You also need to occasionally reshape your data to make the diff smaller. I work on a search app that thrashed for 1.2s every time new search results came in. The problem was that the results were invalidating a recursive menu component which was re-rendering 4 times per update. Avoiding the invalidation fixed the specific delay but the menu was still slow. Switching the menu's data organization from at tree of objects with `open` attrs to a static tree + open path and only rendering the visible nodes solved the perf problems in the app.
I'm not the least bit surprised they discarded bindings in iOS, then (effectively) discarded KVO in Swift.
Next time, try playing with creating an observer protocol:
@protocol MyThingObserver
@optional
- (void)myThing:(MyThing *)thing didChangeIntegerValue:(NSUInteger)newValue;
- (void)numberOfItemsDidChangeInThing:(MyThing *)thing;
@end
Then you have strong typing, compile-time validation, additional context, and plays much nicer with the land of tomorrow (Swift).Coupled with immutable value types, you're going to make your own life way easier, I promise.
As I mentioned in my previous post, I felt KVO was a really interesting design path to be sure, but I agree with you it had its fair share of issues. That being said, observer patterns are just incremental improvements on this. Conceptually its still the same: figuring out ways of getting different parts of a system to eventually "settle" on the same value. Sure, strict typing and whatnot can make this safer, but its ultimately a lot of code that has no real connection to the actual problem your program is trying to solve.
Personally I find immutable everything types (through persistent data structures) combined with immediate mode programming for rendering has more or less taken away the cognitive overhead I used to have around this set of "problems". You have a model, that can lead to a new model in the future. You then have a render function that is a function of this model. Its completely deterministic, there is only one path things can go down, you can grab the state of your program at any time and keep re-rendering it to figure out whats going on -- there's no "implicit" conglomeration of state through the value of all the free variables in your program at any particular point in time and their knowledge of each other.
If I were to return to iOS programming today, I'd probably give React Native a stab. To me tomorrow land is being able to change code and see it live update without recompile or provisioning profiles or what have you.
Is there a more idiomatic way to work around this in JS other than Object.observe if you don't want to resort to dirty checking or patching the library to provide a callback?